bridge: Rate limit default address warnings.
[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         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 10);
1409         memcpy(ea, br->default_ea, ETH_ADDR_LEN);
1410         *hw_addr_iface = NULL;
1411         VLOG_WARN_RL(&rl, "bridge %s: using default bridge Ethernet "
1412                      "address "ETH_ADDR_FMT, br->name, ETH_ADDR_ARGS(ea));
1413     }
1414
1415     hmapx_destroy(&mirror_output_ports);
1416 }
1417
1418 /* Choose and returns the datapath ID for bridge 'br' given that the bridge
1419  * Ethernet address is 'bridge_ea'.  If 'bridge_ea' is the Ethernet address of
1420  * an interface on 'br', then that interface must be passed in as
1421  * 'hw_addr_iface'; if 'bridge_ea' was derived some other way, then
1422  * 'hw_addr_iface' must be passed in as a null pointer. */
1423 static uint64_t
1424 bridge_pick_datapath_id(struct bridge *br,
1425                         const uint8_t bridge_ea[ETH_ADDR_LEN],
1426                         struct iface *hw_addr_iface)
1427 {
1428     /*
1429      * The procedure for choosing a bridge MAC address will, in the most
1430      * ordinary case, also choose a unique MAC that we can use as a datapath
1431      * ID.  In some special cases, though, multiple bridges will end up with
1432      * the same MAC address.  This is OK for the bridges, but it will confuse
1433      * the OpenFlow controller, because each datapath needs a unique datapath
1434      * ID.
1435      *
1436      * Datapath IDs must be unique.  It is also very desirable that they be
1437      * stable from one run to the next, so that policy set on a datapath
1438      * "sticks".
1439      */
1440     const char *datapath_id;
1441     uint64_t dpid;
1442
1443     datapath_id = ovsrec_bridge_get_other_config_value(br->cfg, "datapath-id",
1444                                                        NULL);
1445     if (datapath_id && dpid_from_string(datapath_id, &dpid)) {
1446         return dpid;
1447     }
1448
1449     if (!hw_addr_iface) {
1450         /*
1451          * A purely internal bridge, that is, one that has no non-virtual
1452          * network devices on it at all, is difficult because it has no
1453          * natural unique identifier at all.
1454          *
1455          * When the host is a XenServer, we handle this case by hashing the
1456          * host's UUID with the name of the bridge.  Names of bridges are
1457          * persistent across XenServer reboots, although they can be reused if
1458          * an internal network is destroyed and then a new one is later
1459          * created, so this is fairly effective.
1460          *
1461          * When the host is not a XenServer, we punt by using a random MAC
1462          * address on each run.
1463          */
1464         const char *host_uuid = xenserver_get_host_uuid();
1465         if (host_uuid) {
1466             char *combined = xasprintf("%s,%s", host_uuid, br->name);
1467             dpid = dpid_from_hash(combined, strlen(combined));
1468             free(combined);
1469             return dpid;
1470         }
1471     }
1472
1473     return eth_addr_to_uint64(bridge_ea);
1474 }
1475
1476 static uint64_t
1477 dpid_from_hash(const void *data, size_t n)
1478 {
1479     uint8_t hash[SHA1_DIGEST_SIZE];
1480
1481     BUILD_ASSERT_DECL(sizeof hash >= ETH_ADDR_LEN);
1482     sha1_bytes(data, n, hash);
1483     eth_addr_mark_random(hash);
1484     return eth_addr_to_uint64(hash);
1485 }
1486
1487 static void
1488 iface_refresh_status(struct iface *iface)
1489 {
1490     struct shash sh;
1491
1492     enum netdev_features current;
1493     enum netdev_flags flags;
1494     int64_t bps;
1495     int mtu;
1496     int64_t mtu_64;
1497     int error;
1498
1499     if (iface_is_synthetic(iface)) {
1500         return;
1501     }
1502
1503     shash_init(&sh);
1504
1505     if (!netdev_get_drv_info(iface->netdev, &sh)) {
1506         size_t n;
1507         char **keys, **values;
1508
1509         shash_to_ovs_idl_map(&sh, &keys, &values, &n);
1510         ovsrec_interface_set_status(iface->cfg, keys, values, n);
1511
1512         free(keys);
1513         free(values);
1514     } else {
1515         ovsrec_interface_set_status(iface->cfg, NULL, NULL, 0);
1516     }
1517
1518     shash_destroy_free_data(&sh);
1519
1520     error = netdev_get_flags(iface->netdev, &flags);
1521     if (!error) {
1522         ovsrec_interface_set_admin_state(iface->cfg,
1523                                          flags & NETDEV_UP ? "up" : "down");
1524     }
1525     else {
1526         ovsrec_interface_set_admin_state(iface->cfg, NULL);
1527     }
1528
1529     error = netdev_get_features(iface->netdev, &current, NULL, NULL, NULL);
1530     if (!error) {
1531         ovsrec_interface_set_duplex(iface->cfg,
1532                                     netdev_features_is_full_duplex(current)
1533                                     ? "full" : "half");
1534         /* warning: uint64_t -> int64_t conversion */
1535         bps = netdev_features_to_bps(current);
1536         ovsrec_interface_set_link_speed(iface->cfg, &bps, 1);
1537     }
1538     else {
1539         ovsrec_interface_set_duplex(iface->cfg, NULL);
1540         ovsrec_interface_set_link_speed(iface->cfg, NULL, 0);
1541     }
1542
1543     error = netdev_get_mtu(iface->netdev, &mtu);
1544     if (!error) {
1545         mtu_64 = mtu;
1546         ovsrec_interface_set_mtu(iface->cfg, &mtu_64, 1);
1547     }
1548     else {
1549         ovsrec_interface_set_mtu(iface->cfg, NULL, 0);
1550     }
1551 }
1552
1553 /* Writes 'iface''s CFM statistics to the database. */
1554 static void
1555 iface_refresh_cfm_stats(struct iface *iface)
1556 {
1557     const struct ovsrec_interface *cfg = iface->cfg;
1558     int fault, error;
1559     const uint64_t *rmps;
1560     size_t n_rmps;
1561     int health;
1562
1563     if (iface_is_synthetic(iface)) {
1564         return;
1565     }
1566
1567     fault = ofproto_port_get_cfm_fault(iface->port->bridge->ofproto,
1568                                        iface->ofp_port);
1569     if (fault >= 0) {
1570         const char *reasons[CFM_FAULT_N_REASONS];
1571         bool fault_bool = fault;
1572         size_t i, j;
1573
1574         j = 0;
1575         for (i = 0; i < CFM_FAULT_N_REASONS; i++) {
1576             int reason = 1 << i;
1577             if (fault & reason) {
1578                 reasons[j++] = cfm_fault_reason_to_str(reason);
1579             }
1580         }
1581
1582         ovsrec_interface_set_cfm_fault(cfg, &fault_bool, 1);
1583         ovsrec_interface_set_cfm_fault_status(cfg, (char **) reasons, j);
1584     } else {
1585         ovsrec_interface_set_cfm_fault(cfg, NULL, 0);
1586         ovsrec_interface_set_cfm_fault_status(cfg, NULL, 0);
1587     }
1588
1589     error = ofproto_port_get_cfm_remote_mpids(iface->port->bridge->ofproto,
1590                                               iface->ofp_port, &rmps, &n_rmps);
1591     if (error >= 0) {
1592         ovsrec_interface_set_cfm_remote_mpids(cfg, (const int64_t *)rmps,
1593                                               n_rmps);
1594     } else {
1595         ovsrec_interface_set_cfm_remote_mpids(cfg, NULL, 0);
1596     }
1597
1598     health = ofproto_port_get_cfm_health(iface->port->bridge->ofproto,
1599                                         iface->ofp_port);
1600     if (health >= 0) {
1601         int64_t cfm_health = health;
1602         ovsrec_interface_set_cfm_health(cfg, &cfm_health, 1);
1603     } else {
1604         ovsrec_interface_set_cfm_health(cfg, NULL, 0);
1605     }
1606 }
1607
1608 static void
1609 iface_refresh_stats(struct iface *iface)
1610 {
1611 #define IFACE_STATS                             \
1612     IFACE_STAT(rx_packets,      "rx_packets")   \
1613     IFACE_STAT(tx_packets,      "tx_packets")   \
1614     IFACE_STAT(rx_bytes,        "rx_bytes")     \
1615     IFACE_STAT(tx_bytes,        "tx_bytes")     \
1616     IFACE_STAT(rx_dropped,      "rx_dropped")   \
1617     IFACE_STAT(tx_dropped,      "tx_dropped")   \
1618     IFACE_STAT(rx_errors,       "rx_errors")    \
1619     IFACE_STAT(tx_errors,       "tx_errors")    \
1620     IFACE_STAT(rx_frame_errors, "rx_frame_err") \
1621     IFACE_STAT(rx_over_errors,  "rx_over_err")  \
1622     IFACE_STAT(rx_crc_errors,   "rx_crc_err")   \
1623     IFACE_STAT(collisions,      "collisions")
1624
1625 #define IFACE_STAT(MEMBER, NAME) NAME,
1626     static char *keys[] = { IFACE_STATS };
1627 #undef IFACE_STAT
1628     int64_t values[ARRAY_SIZE(keys)];
1629     int i;
1630
1631     struct netdev_stats stats;
1632
1633     if (iface_is_synthetic(iface)) {
1634         return;
1635     }
1636
1637     /* Intentionally ignore return value, since errors will set 'stats' to
1638      * all-1s, and we will deal with that correctly below. */
1639     netdev_get_stats(iface->netdev, &stats);
1640
1641     /* Copy statistics into values[] array. */
1642     i = 0;
1643 #define IFACE_STAT(MEMBER, NAME) values[i++] = stats.MEMBER;
1644     IFACE_STATS;
1645 #undef IFACE_STAT
1646     assert(i == ARRAY_SIZE(keys));
1647
1648     ovsrec_interface_set_statistics(iface->cfg, keys, values,
1649                                     ARRAY_SIZE(keys));
1650 #undef IFACE_STATS
1651 }
1652
1653 static void
1654 br_refresh_stp_status(struct bridge *br)
1655 {
1656     struct ofproto *ofproto = br->ofproto;
1657     struct ofproto_stp_status status;
1658     char *keys[3], *values[3];
1659     size_t i;
1660
1661     if (ofproto_get_stp_status(ofproto, &status)) {
1662         return;
1663     }
1664
1665     if (!status.enabled) {
1666         ovsrec_bridge_set_status(br->cfg, NULL, NULL, 0);
1667         return;
1668     }
1669
1670     keys[0] = "stp_bridge_id",
1671     values[0] = xasprintf(STP_ID_FMT, STP_ID_ARGS(status.bridge_id));
1672     keys[1] = "stp_designated_root",
1673     values[1] = xasprintf(STP_ID_FMT, STP_ID_ARGS(status.designated_root));
1674     keys[2] = "stp_root_path_cost",
1675     values[2] = xasprintf("%d", status.root_path_cost);
1676
1677     ovsrec_bridge_set_status(br->cfg, keys, values, ARRAY_SIZE(values));
1678
1679     for (i = 0; i < ARRAY_SIZE(values); i++) {
1680         free(values[i]);
1681     }
1682 }
1683
1684 static void
1685 port_refresh_stp_status(struct port *port)
1686 {
1687     struct ofproto *ofproto = port->bridge->ofproto;
1688     struct iface *iface;
1689     struct ofproto_port_stp_status status;
1690     char *keys[4];
1691     char *str_values[4];
1692     int64_t int_values[3];
1693     size_t i;
1694
1695     if (port_is_synthetic(port)) {
1696         return;
1697     }
1698
1699     /* STP doesn't currently support bonds. */
1700     if (!list_is_singleton(&port->ifaces)) {
1701         ovsrec_port_set_status(port->cfg, NULL, NULL, 0);
1702         return;
1703     }
1704
1705     iface = CONTAINER_OF(list_front(&port->ifaces), struct iface, port_elem);
1706
1707     if (ofproto_port_get_stp_status(ofproto, iface->ofp_port, &status)) {
1708         return;
1709     }
1710
1711     if (!status.enabled) {
1712         ovsrec_port_set_status(port->cfg, NULL, NULL, 0);
1713         ovsrec_port_set_statistics(port->cfg, NULL, NULL, 0);
1714         return;
1715     }
1716
1717     /* Set Status column. */
1718     keys[0] = "stp_port_id";
1719     str_values[0] = xasprintf(STP_PORT_ID_FMT, status.port_id);
1720     keys[1] = "stp_state";
1721     str_values[1] = xstrdup(stp_state_name(status.state));
1722     keys[2] = "stp_sec_in_state";
1723     str_values[2] = xasprintf("%u", status.sec_in_state);
1724     keys[3] = "stp_role";
1725     str_values[3] = xstrdup(stp_role_name(status.role));
1726
1727     ovsrec_port_set_status(port->cfg, keys, str_values,
1728                            ARRAY_SIZE(str_values));
1729
1730     for (i = 0; i < ARRAY_SIZE(str_values); i++) {
1731         free(str_values[i]);
1732     }
1733
1734     /* Set Statistics column. */
1735     keys[0] = "stp_tx_count";
1736     int_values[0] = status.tx_count;
1737     keys[1] = "stp_rx_count";
1738     int_values[1] = status.rx_count;
1739     keys[2] = "stp_error_count";
1740     int_values[2] = status.error_count;
1741
1742     ovsrec_port_set_statistics(port->cfg, keys, int_values,
1743                                ARRAY_SIZE(int_values));
1744 }
1745
1746 static bool
1747 enable_system_stats(const struct ovsrec_open_vswitch *cfg)
1748 {
1749     const char *enable;
1750
1751     /* Use other-config:enable-system-stats by preference. */
1752     enable = ovsrec_open_vswitch_get_other_config_value(cfg,
1753                                                         "enable-statistics",
1754                                                         NULL);
1755     if (enable) {
1756         return !strcmp(enable, "true");
1757     }
1758
1759     /* Disable by default. */
1760     return false;
1761 }
1762
1763 static void
1764 refresh_system_stats(const struct ovsrec_open_vswitch *cfg)
1765 {
1766     struct ovsdb_datum datum;
1767     struct shash stats;
1768
1769     shash_init(&stats);
1770     if (enable_system_stats(cfg)) {
1771         get_system_stats(&stats);
1772     }
1773
1774     ovsdb_datum_from_shash(&datum, &stats);
1775     ovsdb_idl_txn_write(&cfg->header_, &ovsrec_open_vswitch_col_statistics,
1776                         &datum);
1777 }
1778
1779 static inline const char *
1780 nx_role_to_str(enum nx_role role)
1781 {
1782     switch (role) {
1783     case NX_ROLE_OTHER:
1784         return "other";
1785     case NX_ROLE_MASTER:
1786         return "master";
1787     case NX_ROLE_SLAVE:
1788         return "slave";
1789     default:
1790         return "*** INVALID ROLE ***";
1791     }
1792 }
1793
1794 static void
1795 refresh_controller_status(void)
1796 {
1797     struct bridge *br;
1798     struct shash info;
1799     const struct ovsrec_controller *cfg;
1800
1801     shash_init(&info);
1802
1803     /* Accumulate status for controllers on all bridges. */
1804     HMAP_FOR_EACH (br, node, &all_bridges) {
1805         ofproto_get_ofproto_controller_info(br->ofproto, &info);
1806     }
1807
1808     /* Update each controller in the database with current status. */
1809     OVSREC_CONTROLLER_FOR_EACH(cfg, idl) {
1810         struct ofproto_controller_info *cinfo =
1811             shash_find_data(&info, cfg->target);
1812
1813         if (cinfo) {
1814             ovsrec_controller_set_is_connected(cfg, cinfo->is_connected);
1815             ovsrec_controller_set_role(cfg, nx_role_to_str(cinfo->role));
1816             ovsrec_controller_set_status(cfg, (char **) cinfo->pairs.keys,
1817                                          (char **) cinfo->pairs.values,
1818                                          cinfo->pairs.n);
1819         } else {
1820             ovsrec_controller_set_is_connected(cfg, false);
1821             ovsrec_controller_set_role(cfg, NULL);
1822             ovsrec_controller_set_status(cfg, NULL, NULL, 0);
1823         }
1824     }
1825
1826     ofproto_free_ofproto_controller_info(&info);
1827 }
1828
1829 static void
1830 refresh_cfm_stats(void)
1831 {
1832     static struct ovsdb_idl_txn *txn = NULL;
1833
1834     if (!txn) {
1835         struct bridge *br;
1836
1837         txn = ovsdb_idl_txn_create(idl);
1838
1839         HMAP_FOR_EACH (br, node, &all_bridges) {
1840             struct iface *iface;
1841
1842             HMAP_FOR_EACH (iface, name_node, &br->iface_by_name) {
1843                 iface_refresh_cfm_stats(iface);
1844             }
1845         }
1846     }
1847
1848     if (ovsdb_idl_txn_commit(txn) != TXN_INCOMPLETE) {
1849         ovsdb_idl_txn_destroy(txn);
1850         txn = NULL;
1851     }
1852 }
1853
1854 /* Performs periodic activity required by bridges that needs to be done with
1855  * the least possible latency.
1856  *
1857  * It makes sense to call this function a couple of times per poll loop, to
1858  * provide a significant performance boost on some benchmarks with ofprotos
1859  * that use the ofproto-dpif implementation. */
1860 void
1861 bridge_run_fast(void)
1862 {
1863     struct bridge *br;
1864
1865     HMAP_FOR_EACH (br, node, &all_bridges) {
1866         ofproto_run_fast(br->ofproto);
1867     }
1868 }
1869
1870 void
1871 bridge_run(void)
1872 {
1873     const struct ovsrec_open_vswitch *cfg;
1874
1875     bool vlan_splinters_changed;
1876     struct bridge *br;
1877
1878     /* (Re)configure if necessary. */
1879     ovsdb_idl_run(idl);
1880     if (ovsdb_idl_is_lock_contended(idl)) {
1881         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 1);
1882         struct bridge *br, *next_br;
1883
1884         VLOG_ERR_RL(&rl, "another ovs-vswitchd process is running, "
1885                     "disabling this process until it goes away");
1886
1887         HMAP_FOR_EACH_SAFE (br, next_br, node, &all_bridges) {
1888             bridge_destroy(br);
1889         }
1890         return;
1891     } else if (!ovsdb_idl_has_lock(idl)) {
1892         return;
1893     }
1894     cfg = ovsrec_open_vswitch_first(idl);
1895
1896     /* Let each bridge do the work that it needs to do. */
1897     HMAP_FOR_EACH (br, node, &all_bridges) {
1898         ofproto_run(br->ofproto);
1899     }
1900
1901     /* Re-configure SSL.  We do this on every trip through the main loop,
1902      * instead of just when the database changes, because the contents of the
1903      * key and certificate files can change without the database changing.
1904      *
1905      * We do this before bridge_reconfigure() because that function might
1906      * initiate SSL connections and thus requires SSL to be configured. */
1907     if (cfg && cfg->ssl) {
1908         const struct ovsrec_ssl *ssl = cfg->ssl;
1909
1910         stream_ssl_set_key_and_cert(ssl->private_key, ssl->certificate);
1911         stream_ssl_set_ca_cert_file(ssl->ca_cert, ssl->bootstrap_ca_cert);
1912     }
1913
1914     /* If VLAN splinters are in use, then we need to reconfigure if VLAN usage
1915      * has changed. */
1916     vlan_splinters_changed = false;
1917     if (vlan_splinters_enabled_anywhere) {
1918         HMAP_FOR_EACH (br, node, &all_bridges) {
1919             if (ofproto_has_vlan_usage_changed(br->ofproto)) {
1920                 vlan_splinters_changed = true;
1921                 break;
1922             }
1923         }
1924     }
1925
1926     if (ovsdb_idl_get_seqno(idl) != idl_seqno || vlan_splinters_changed) {
1927         idl_seqno = ovsdb_idl_get_seqno(idl);
1928         if (cfg) {
1929             struct ovsdb_idl_txn *txn = ovsdb_idl_txn_create(idl);
1930
1931             bridge_reconfigure(cfg);
1932
1933             ovsrec_open_vswitch_set_cur_cfg(cfg, cfg->next_cfg);
1934             ovsdb_idl_txn_commit(txn);
1935             ovsdb_idl_txn_destroy(txn); /* XXX */
1936         } else {
1937             /* We still need to reconfigure to avoid dangling pointers to
1938              * now-destroyed ovsrec structures inside bridge data. */
1939             static const struct ovsrec_open_vswitch null_cfg;
1940
1941             bridge_reconfigure(&null_cfg);
1942         }
1943     }
1944
1945     /* Refresh system and interface stats if necessary. */
1946     if (time_msec() >= stats_timer) {
1947         if (cfg) {
1948             struct ovsdb_idl_txn *txn;
1949
1950             txn = ovsdb_idl_txn_create(idl);
1951             HMAP_FOR_EACH (br, node, &all_bridges) {
1952                 struct port *port;
1953                 struct mirror *m;
1954
1955                 HMAP_FOR_EACH (port, hmap_node, &br->ports) {
1956                     struct iface *iface;
1957
1958                     LIST_FOR_EACH (iface, port_elem, &port->ifaces) {
1959                         iface_refresh_stats(iface);
1960                         iface_refresh_status(iface);
1961                     }
1962                 }
1963
1964                 HMAP_FOR_EACH (m, hmap_node, &br->mirrors) {
1965                     mirror_refresh_stats(m);
1966                 }
1967
1968             }
1969             refresh_system_stats(cfg);
1970             refresh_controller_status();
1971             ovsdb_idl_txn_commit(txn);
1972             ovsdb_idl_txn_destroy(txn); /* XXX */
1973         }
1974
1975         stats_timer = time_msec() + STATS_INTERVAL;
1976     }
1977
1978     if (time_msec() >= db_limiter) {
1979         struct ovsdb_idl_txn *txn;
1980
1981         txn = ovsdb_idl_txn_create(idl);
1982         HMAP_FOR_EACH (br, node, &all_bridges) {
1983             struct iface *iface;
1984             struct port *port;
1985
1986             br_refresh_stp_status(br);
1987
1988             HMAP_FOR_EACH (port, hmap_node, &br->ports) {
1989                 port_refresh_stp_status(port);
1990             }
1991
1992             HMAP_FOR_EACH (iface, name_node, &br->iface_by_name) {
1993                 const char *link_state;
1994                 int64_t link_resets;
1995                 int current;
1996
1997                 if (iface_is_synthetic(iface)) {
1998                     continue;
1999                 }
2000
2001                 current = ofproto_port_is_lacp_current(br->ofproto,
2002                                                        iface->ofp_port);
2003                 if (current >= 0) {
2004                     bool bl = current;
2005                     ovsrec_interface_set_lacp_current(iface->cfg, &bl, 1);
2006                 } else {
2007                     ovsrec_interface_set_lacp_current(iface->cfg, NULL, 0);
2008                 }
2009
2010                 link_state = netdev_get_carrier(iface->netdev) ? "up" : "down";
2011                 ovsrec_interface_set_link_state(iface->cfg, link_state);
2012
2013                 link_resets = netdev_get_carrier_resets(iface->netdev);
2014                 ovsrec_interface_set_link_resets(iface->cfg, &link_resets, 1);
2015             }
2016         }
2017
2018         if (ovsdb_idl_txn_commit(txn) != TXN_UNCHANGED) {
2019             db_limiter = time_msec() + DB_LIMIT_INTERVAL;
2020         }
2021         ovsdb_idl_txn_destroy(txn);
2022     }
2023
2024     refresh_cfm_stats();
2025 }
2026
2027 void
2028 bridge_wait(void)
2029 {
2030     ovsdb_idl_wait(idl);
2031     if (!hmap_is_empty(&all_bridges)) {
2032         struct bridge *br;
2033
2034         HMAP_FOR_EACH (br, node, &all_bridges) {
2035             ofproto_wait(br->ofproto);
2036         }
2037         poll_timer_wait_until(stats_timer);
2038
2039         if (db_limiter > time_msec()) {
2040             poll_timer_wait_until(db_limiter);
2041         }
2042     }
2043 }
2044 \f
2045 /* QoS unixctl user interface functions. */
2046
2047 struct qos_unixctl_show_cbdata {
2048     struct ds *ds;
2049     struct iface *iface;
2050 };
2051
2052 static void
2053 qos_unixctl_show_cb(unsigned int queue_id,
2054                     const struct shash *details,
2055                     void *aux)
2056 {
2057     struct qos_unixctl_show_cbdata *data = aux;
2058     struct ds *ds = data->ds;
2059     struct iface *iface = data->iface;
2060     struct netdev_queue_stats stats;
2061     struct shash_node *node;
2062     int error;
2063
2064     ds_put_cstr(ds, "\n");
2065     if (queue_id) {
2066         ds_put_format(ds, "Queue %u:\n", queue_id);
2067     } else {
2068         ds_put_cstr(ds, "Default:\n");
2069     }
2070
2071     SHASH_FOR_EACH (node, details) {
2072         ds_put_format(ds, "\t%s: %s\n", node->name, (char *)node->data);
2073     }
2074
2075     error = netdev_get_queue_stats(iface->netdev, queue_id, &stats);
2076     if (!error) {
2077         if (stats.tx_packets != UINT64_MAX) {
2078             ds_put_format(ds, "\ttx_packets: %"PRIu64"\n", stats.tx_packets);
2079         }
2080
2081         if (stats.tx_bytes != UINT64_MAX) {
2082             ds_put_format(ds, "\ttx_bytes: %"PRIu64"\n", stats.tx_bytes);
2083         }
2084
2085         if (stats.tx_errors != UINT64_MAX) {
2086             ds_put_format(ds, "\ttx_errors: %"PRIu64"\n", stats.tx_errors);
2087         }
2088     } else {
2089         ds_put_format(ds, "\tFailed to get statistics for queue %u: %s",
2090                       queue_id, strerror(error));
2091     }
2092 }
2093
2094 static void
2095 qos_unixctl_show(struct unixctl_conn *conn, int argc OVS_UNUSED,
2096                  const char *argv[], void *aux OVS_UNUSED)
2097 {
2098     struct ds ds = DS_EMPTY_INITIALIZER;
2099     struct shash sh = SHASH_INITIALIZER(&sh);
2100     struct iface *iface;
2101     const char *type;
2102     struct shash_node *node;
2103     struct qos_unixctl_show_cbdata data;
2104     int error;
2105
2106     iface = iface_find(argv[1]);
2107     if (!iface) {
2108         unixctl_command_reply_error(conn, "no such interface");
2109         return;
2110     }
2111
2112     netdev_get_qos(iface->netdev, &type, &sh);
2113
2114     if (*type != '\0') {
2115         ds_put_format(&ds, "QoS: %s %s\n", iface->name, type);
2116
2117         SHASH_FOR_EACH (node, &sh) {
2118             ds_put_format(&ds, "%s: %s\n", node->name, (char *)node->data);
2119         }
2120
2121         data.ds = &ds;
2122         data.iface = iface;
2123         error = netdev_dump_queues(iface->netdev, qos_unixctl_show_cb, &data);
2124
2125         if (error) {
2126             ds_put_format(&ds, "failed to dump queues: %s", strerror(error));
2127         }
2128         unixctl_command_reply(conn, ds_cstr(&ds));
2129     } else {
2130         ds_put_format(&ds, "QoS not configured on %s\n", iface->name);
2131         unixctl_command_reply_error(conn, ds_cstr(&ds));
2132     }
2133
2134     shash_destroy_free_data(&sh);
2135     ds_destroy(&ds);
2136 }
2137 \f
2138 /* Bridge reconfiguration functions. */
2139 static void
2140 bridge_create(const struct ovsrec_bridge *br_cfg)
2141 {
2142     struct bridge *br;
2143
2144     assert(!bridge_lookup(br_cfg->name));
2145     br = xzalloc(sizeof *br);
2146
2147     br->name = xstrdup(br_cfg->name);
2148     br->type = xstrdup(ofproto_normalize_type(br_cfg->datapath_type));
2149     br->cfg = br_cfg;
2150
2151     /* Derive the default Ethernet address from the bridge's UUID.  This should
2152      * be unique and it will be stable between ovs-vswitchd runs.  */
2153     memcpy(br->default_ea, &br_cfg->header_.uuid, ETH_ADDR_LEN);
2154     eth_addr_mark_random(br->default_ea);
2155
2156     hmap_init(&br->ports);
2157     hmap_init(&br->ifaces);
2158     hmap_init(&br->iface_by_name);
2159     hmap_init(&br->mirrors);
2160
2161     hmap_insert(&all_bridges, &br->node, hash_string(br->name, 0));
2162 }
2163
2164 static void
2165 bridge_destroy(struct bridge *br)
2166 {
2167     if (br) {
2168         struct mirror *mirror, *next_mirror;
2169         struct port *port, *next_port;
2170
2171         HMAP_FOR_EACH_SAFE (port, next_port, hmap_node, &br->ports) {
2172             port_destroy(port);
2173         }
2174         HMAP_FOR_EACH_SAFE (mirror, next_mirror, hmap_node, &br->mirrors) {
2175             mirror_destroy(mirror);
2176         }
2177         hmap_remove(&all_bridges, &br->node);
2178         ofproto_destroy(br->ofproto);
2179         hmap_destroy(&br->ifaces);
2180         hmap_destroy(&br->ports);
2181         hmap_destroy(&br->iface_by_name);
2182         hmap_destroy(&br->mirrors);
2183         free(br->name);
2184         free(br->type);
2185         free(br);
2186     }
2187 }
2188
2189 static struct bridge *
2190 bridge_lookup(const char *name)
2191 {
2192     struct bridge *br;
2193
2194     HMAP_FOR_EACH_WITH_HASH (br, node, hash_string(name, 0), &all_bridges) {
2195         if (!strcmp(br->name, name)) {
2196             return br;
2197         }
2198     }
2199     return NULL;
2200 }
2201
2202 /* Handle requests for a listing of all flows known by the OpenFlow
2203  * stack, including those normally hidden. */
2204 static void
2205 bridge_unixctl_dump_flows(struct unixctl_conn *conn, int argc OVS_UNUSED,
2206                           const char *argv[], void *aux OVS_UNUSED)
2207 {
2208     struct bridge *br;
2209     struct ds results;
2210
2211     br = bridge_lookup(argv[1]);
2212     if (!br) {
2213         unixctl_command_reply_error(conn, "Unknown bridge");
2214         return;
2215     }
2216
2217     ds_init(&results);
2218     ofproto_get_all_flows(br->ofproto, &results);
2219
2220     unixctl_command_reply(conn, ds_cstr(&results));
2221     ds_destroy(&results);
2222 }
2223
2224 /* "bridge/reconnect [BRIDGE]": makes BRIDGE drop all of its controller
2225  * connections and reconnect.  If BRIDGE is not specified, then all bridges
2226  * drop their controller connections and reconnect. */
2227 static void
2228 bridge_unixctl_reconnect(struct unixctl_conn *conn, int argc,
2229                          const char *argv[], void *aux OVS_UNUSED)
2230 {
2231     struct bridge *br;
2232     if (argc > 1) {
2233         br = bridge_lookup(argv[1]);
2234         if (!br) {
2235             unixctl_command_reply_error(conn,  "Unknown bridge");
2236             return;
2237         }
2238         ofproto_reconnect_controllers(br->ofproto);
2239     } else {
2240         HMAP_FOR_EACH (br, node, &all_bridges) {
2241             ofproto_reconnect_controllers(br->ofproto);
2242         }
2243     }
2244     unixctl_command_reply(conn, NULL);
2245 }
2246
2247 static size_t
2248 bridge_get_controllers(const struct bridge *br,
2249                        struct ovsrec_controller ***controllersp)
2250 {
2251     struct ovsrec_controller **controllers;
2252     size_t n_controllers;
2253
2254     controllers = br->cfg->controller;
2255     n_controllers = br->cfg->n_controller;
2256
2257     if (n_controllers == 1 && !strcmp(controllers[0]->target, "none")) {
2258         controllers = NULL;
2259         n_controllers = 0;
2260     }
2261
2262     if (controllersp) {
2263         *controllersp = controllers;
2264     }
2265     return n_controllers;
2266 }
2267
2268 /* Adds and deletes "struct port"s and "struct iface"s under 'br' to match
2269  * those configured in 'br->cfg'. */
2270 static void
2271 bridge_add_del_ports(struct bridge *br,
2272                      const unsigned long int *splinter_vlans)
2273 {
2274     struct port *port, *next;
2275     struct shash_node *node;
2276     struct shash new_ports;
2277     size_t i;
2278
2279     /* Collect new ports. */
2280     shash_init(&new_ports);
2281     for (i = 0; i < br->cfg->n_ports; i++) {
2282         const char *name = br->cfg->ports[i]->name;
2283         if (!shash_add_once(&new_ports, name, br->cfg->ports[i])) {
2284             VLOG_WARN("bridge %s: %s specified twice as bridge port",
2285                       br->name, name);
2286         }
2287     }
2288     if (bridge_get_controllers(br, NULL)
2289         && !shash_find(&new_ports, br->name)) {
2290         VLOG_WARN("bridge %s: no port named %s, synthesizing one",
2291                   br->name, br->name);
2292
2293         br->synth_local_port.interfaces = &br->synth_local_ifacep;
2294         br->synth_local_port.n_interfaces = 1;
2295         br->synth_local_port.name = br->name;
2296
2297         br->synth_local_iface.name = br->name;
2298         br->synth_local_iface.type = "internal";
2299
2300         br->synth_local_ifacep = &br->synth_local_iface;
2301
2302         shash_add(&new_ports, br->name, &br->synth_local_port);
2303     }
2304
2305     if (splinter_vlans) {
2306         add_vlan_splinter_ports(br, splinter_vlans, &new_ports);
2307     }
2308
2309     /* Get rid of deleted ports.
2310      * Get rid of deleted interfaces on ports that still exist. */
2311     HMAP_FOR_EACH_SAFE (port, next, hmap_node, &br->ports) {
2312         port->cfg = shash_find_data(&new_ports, port->name);
2313         if (!port->cfg) {
2314             port_destroy(port);
2315         } else {
2316             port_del_ifaces(port);
2317         }
2318     }
2319
2320     /* Create new ports.
2321      * Add new interfaces to existing ports. */
2322     SHASH_FOR_EACH (node, &new_ports) {
2323         struct port *port = port_lookup(br, node->name);
2324         if (!port) {
2325             struct ovsrec_port *cfg = node->data;
2326             port = port_create(br, cfg);
2327         }
2328         port_add_ifaces(port);
2329         if (list_is_empty(&port->ifaces)) {
2330             VLOG_WARN("bridge %s: port %s has no interfaces, dropping",
2331                       br->name, port->name);
2332             port_destroy(port);
2333         }
2334     }
2335     shash_destroy(&new_ports);
2336 }
2337
2338 /* Initializes 'oc' appropriately as a management service controller for
2339  * 'br'.
2340  *
2341  * The caller must free oc->target when it is no longer needed. */
2342 static void
2343 bridge_ofproto_controller_for_mgmt(const struct bridge *br,
2344                                    struct ofproto_controller *oc)
2345 {
2346     oc->target = xasprintf("punix:%s/%s.mgmt", ovs_rundir(), br->name);
2347     oc->max_backoff = 0;
2348     oc->probe_interval = 60;
2349     oc->band = OFPROTO_OUT_OF_BAND;
2350     oc->rate_limit = 0;
2351     oc->burst_limit = 0;
2352     oc->enable_async_msgs = true;
2353 }
2354
2355 /* Converts ovsrec_controller 'c' into an ofproto_controller in 'oc'.  */
2356 static void
2357 bridge_ofproto_controller_from_ovsrec(const struct ovsrec_controller *c,
2358                                       struct ofproto_controller *oc)
2359 {
2360     const char *config_str;
2361
2362     oc->target = c->target;
2363     oc->max_backoff = c->max_backoff ? *c->max_backoff / 1000 : 8;
2364     oc->probe_interval = c->inactivity_probe ? *c->inactivity_probe / 1000 : 5;
2365     oc->band = (!c->connection_mode || !strcmp(c->connection_mode, "in-band")
2366                 ? OFPROTO_IN_BAND : OFPROTO_OUT_OF_BAND);
2367     oc->rate_limit = c->controller_rate_limit ? *c->controller_rate_limit : 0;
2368     oc->burst_limit = (c->controller_burst_limit
2369                        ? *c->controller_burst_limit : 0);
2370     oc->enable_async_msgs = (!c->enable_async_messages
2371                              || *c->enable_async_messages);
2372     config_str = ovsrec_controller_get_other_config_value(c, "dscp", NULL);
2373     if (config_str) {
2374         oc->dscp = atoi(config_str);
2375     } else {
2376         oc->dscp = DSCP_DEFAULT;
2377     }
2378 }
2379
2380 /* Configures the IP stack for 'br''s local interface properly according to the
2381  * configuration in 'c'.  */
2382 static void
2383 bridge_configure_local_iface_netdev(struct bridge *br,
2384                                     struct ovsrec_controller *c)
2385 {
2386     struct netdev *netdev;
2387     struct in_addr mask, gateway;
2388
2389     struct iface *local_iface;
2390     struct in_addr ip;
2391
2392     /* If there's no local interface or no IP address, give up. */
2393     local_iface = iface_from_ofp_port(br, OFPP_LOCAL);
2394     if (!local_iface || !c->local_ip || !inet_aton(c->local_ip, &ip)) {
2395         return;
2396     }
2397
2398     /* Bring up the local interface. */
2399     netdev = local_iface->netdev;
2400     netdev_turn_flags_on(netdev, NETDEV_UP, true);
2401
2402     /* Configure the IP address and netmask. */
2403     if (!c->local_netmask
2404         || !inet_aton(c->local_netmask, &mask)
2405         || !mask.s_addr) {
2406         mask.s_addr = guess_netmask(ip.s_addr);
2407     }
2408     if (!netdev_set_in4(netdev, ip, mask)) {
2409         VLOG_INFO("bridge %s: configured IP address "IP_FMT", netmask "IP_FMT,
2410                   br->name, IP_ARGS(&ip.s_addr), IP_ARGS(&mask.s_addr));
2411     }
2412
2413     /* Configure the default gateway. */
2414     if (c->local_gateway
2415         && inet_aton(c->local_gateway, &gateway)
2416         && gateway.s_addr) {
2417         if (!netdev_add_router(netdev, gateway)) {
2418             VLOG_INFO("bridge %s: configured gateway "IP_FMT,
2419                       br->name, IP_ARGS(&gateway.s_addr));
2420         }
2421     }
2422 }
2423
2424 /* Returns true if 'a' and 'b' are the same except that any number of slashes
2425  * in either string are treated as equal to any number of slashes in the other,
2426  * e.g. "x///y" is equal to "x/y". */
2427 static bool
2428 equal_pathnames(const char *a, const char *b)
2429 {
2430     while (*a == *b) {
2431         if (*a == '/') {
2432             a += strspn(a, "/");
2433             b += strspn(b, "/");
2434         } else if (*a == '\0') {
2435             return true;
2436         } else {
2437             a++;
2438             b++;
2439         }
2440     }
2441     return false;
2442 }
2443
2444 static void
2445 bridge_configure_remotes(struct bridge *br,
2446                          const struct sockaddr_in *managers, size_t n_managers)
2447 {
2448     const char *disable_ib_str, *queue_id_str;
2449     bool disable_in_band = false;
2450     int queue_id;
2451
2452     struct ovsrec_controller **controllers;
2453     size_t n_controllers;
2454
2455     enum ofproto_fail_mode fail_mode;
2456
2457     struct ofproto_controller *ocs;
2458     size_t n_ocs;
2459     size_t i;
2460
2461     /* Check if we should disable in-band control on this bridge. */
2462     disable_ib_str = ovsrec_bridge_get_other_config_value(br->cfg,
2463                                                           "disable-in-band",
2464                                                           NULL);
2465     if (disable_ib_str && !strcmp(disable_ib_str, "true")) {
2466         disable_in_band = true;
2467     }
2468
2469     /* Set OpenFlow queue ID for in-band control. */
2470     queue_id_str = ovsrec_bridge_get_other_config_value(br->cfg,
2471                                                         "in-band-queue",
2472                                                         NULL);
2473     queue_id = queue_id_str ? strtol(queue_id_str, NULL, 10) : -1;
2474     ofproto_set_in_band_queue(br->ofproto, queue_id);
2475
2476     if (disable_in_band) {
2477         ofproto_set_extra_in_band_remotes(br->ofproto, NULL, 0);
2478     } else {
2479         ofproto_set_extra_in_band_remotes(br->ofproto, managers, n_managers);
2480     }
2481
2482     n_controllers = bridge_get_controllers(br, &controllers);
2483
2484     ocs = xmalloc((n_controllers + 1) * sizeof *ocs);
2485     n_ocs = 0;
2486
2487     bridge_ofproto_controller_for_mgmt(br, &ocs[n_ocs++]);
2488     for (i = 0; i < n_controllers; i++) {
2489         struct ovsrec_controller *c = controllers[i];
2490
2491         if (!strncmp(c->target, "punix:", 6)
2492             || !strncmp(c->target, "unix:", 5)) {
2493             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
2494             char *whitelist;
2495
2496             whitelist = xasprintf("unix:%s/%s.controller",
2497                                   ovs_rundir(), br->name);
2498             if (!equal_pathnames(c->target, whitelist)) {
2499                 /* Prevent remote ovsdb-server users from accessing arbitrary
2500                  * Unix domain sockets and overwriting arbitrary local
2501                  * files. */
2502                 VLOG_ERR_RL(&rl, "bridge %s: Not adding Unix domain socket "
2503                             "controller \"%s\" due to possibility for remote "
2504                             "exploit.  Instead, specify whitelisted \"%s\" or "
2505                             "connect to \"unix:%s/%s.mgmt\" (which is always "
2506                             "available without special configuration).",
2507                             br->name, c->target, whitelist,
2508                             ovs_rundir(), br->name);
2509                 free(whitelist);
2510                 continue;
2511             }
2512
2513             free(whitelist);
2514         }
2515
2516         bridge_configure_local_iface_netdev(br, c);
2517         bridge_ofproto_controller_from_ovsrec(c, &ocs[n_ocs]);
2518         if (disable_in_band) {
2519             ocs[n_ocs].band = OFPROTO_OUT_OF_BAND;
2520         }
2521         n_ocs++;
2522     }
2523
2524     ofproto_set_controllers(br->ofproto, ocs, n_ocs);
2525     free(ocs[0].target); /* From bridge_ofproto_controller_for_mgmt(). */
2526     free(ocs);
2527
2528     /* Set the fail-mode. */
2529     fail_mode = !br->cfg->fail_mode
2530                 || !strcmp(br->cfg->fail_mode, "standalone")
2531                     ? OFPROTO_FAIL_STANDALONE
2532                     : OFPROTO_FAIL_SECURE;
2533     ofproto_set_fail_mode(br->ofproto, fail_mode);
2534
2535     /* Configure OpenFlow controller connection snooping. */
2536     if (!ofproto_has_snoops(br->ofproto)) {
2537         struct sset snoops;
2538
2539         sset_init(&snoops);
2540         sset_add_and_free(&snoops, xasprintf("punix:%s/%s.snoop",
2541                                              ovs_rundir(), br->name));
2542         ofproto_set_snoops(br->ofproto, &snoops);
2543         sset_destroy(&snoops);
2544     }
2545 }
2546
2547 static void
2548 bridge_configure_tables(struct bridge *br)
2549 {
2550     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
2551     int n_tables;
2552     int i, j;
2553
2554     n_tables = ofproto_get_n_tables(br->ofproto);
2555     j = 0;
2556     for (i = 0; i < n_tables; i++) {
2557         struct ofproto_table_settings s;
2558
2559         s.name = NULL;
2560         s.max_flows = UINT_MAX;
2561         s.groups = NULL;
2562         s.n_groups = 0;
2563
2564         if (j < br->cfg->n_flow_tables && i == br->cfg->key_flow_tables[j]) {
2565             struct ovsrec_flow_table *cfg = br->cfg->value_flow_tables[j++];
2566
2567             s.name = cfg->name;
2568             if (cfg->n_flow_limit && *cfg->flow_limit < UINT_MAX) {
2569                 s.max_flows = *cfg->flow_limit;
2570             }
2571             if (cfg->overflow_policy
2572                 && !strcmp(cfg->overflow_policy, "evict")) {
2573                 size_t k;
2574
2575                 s.groups = xmalloc(cfg->n_groups * sizeof *s.groups);
2576                 for (k = 0; k < cfg->n_groups; k++) {
2577                     const char *string = cfg->groups[k];
2578                     char *msg;
2579
2580                     msg = mf_parse_subfield__(&s.groups[k], &string);
2581                     if (msg) {
2582                         VLOG_WARN_RL(&rl, "bridge %s table %d: error parsing "
2583                                      "'groups' (%s)", br->name, i, msg);
2584                         free(msg);
2585                     } else if (*string) {
2586                         VLOG_WARN_RL(&rl, "bridge %s table %d: 'groups' "
2587                                      "element '%s' contains trailing garbage",
2588                                      br->name, i, cfg->groups[k]);
2589                     } else {
2590                         s.n_groups++;
2591                     }
2592                 }
2593             }
2594         }
2595
2596         ofproto_configure_table(br->ofproto, i, &s);
2597
2598         free(s.groups);
2599     }
2600     for (; j < br->cfg->n_flow_tables; j++) {
2601         VLOG_WARN_RL(&rl, "bridge %s: ignoring configuration for flow table "
2602                      "%"PRId64" not supported by this datapath", br->name,
2603                      br->cfg->key_flow_tables[j]);
2604     }
2605 }
2606 \f
2607 /* Port functions. */
2608
2609 static struct port *
2610 port_create(struct bridge *br, const struct ovsrec_port *cfg)
2611 {
2612     struct port *port;
2613
2614     port = xzalloc(sizeof *port);
2615     port->bridge = br;
2616     port->name = xstrdup(cfg->name);
2617     port->cfg = cfg;
2618     list_init(&port->ifaces);
2619
2620     hmap_insert(&br->ports, &port->hmap_node, hash_string(port->name, 0));
2621
2622     VLOG_INFO("created port %s on bridge %s", port->name, br->name);
2623
2624     return port;
2625 }
2626
2627 /* Deletes interfaces from 'port' that are no longer configured for it. */
2628 static void
2629 port_del_ifaces(struct port *port)
2630 {
2631     struct iface *iface, *next;
2632     struct sset new_ifaces;
2633     size_t i;
2634
2635     /* Collect list of new interfaces. */
2636     sset_init(&new_ifaces);
2637     for (i = 0; i < port->cfg->n_interfaces; i++) {
2638         const char *name = port->cfg->interfaces[i]->name;
2639         const char *type = port->cfg->interfaces[i]->name;
2640         if (strcmp(type, "null")) {
2641             sset_add(&new_ifaces, name);
2642         }
2643     }
2644
2645     /* Get rid of deleted interfaces. */
2646     LIST_FOR_EACH_SAFE (iface, next, port_elem, &port->ifaces) {
2647         if (!sset_contains(&new_ifaces, iface->name)) {
2648             iface_destroy(iface);
2649         }
2650     }
2651
2652     sset_destroy(&new_ifaces);
2653 }
2654
2655 /* Adds new interfaces to 'port' and updates 'type' and 'cfg' members of
2656  * existing ones. */
2657 static void
2658 port_add_ifaces(struct port *port)
2659 {
2660     struct shash new_ifaces;
2661     struct shash_node *node;
2662     size_t i;
2663
2664     /* Collect new ifaces. */
2665     shash_init(&new_ifaces);
2666     for (i = 0; i < port->cfg->n_interfaces; i++) {
2667         const struct ovsrec_interface *cfg = port->cfg->interfaces[i];
2668         if (strcmp(cfg->type, "null")
2669             && !shash_add_once(&new_ifaces, cfg->name, cfg)) {
2670             VLOG_WARN("port %s: %s specified twice as port interface",
2671                       port->name, cfg->name);
2672             iface_clear_db_record(cfg);
2673         }
2674     }
2675
2676     /* Create new interfaces.
2677      * Update interface types and 'cfg' members. */
2678     SHASH_FOR_EACH (node, &new_ifaces) {
2679         const struct ovsrec_interface *cfg = node->data;
2680         const char *iface_name = node->name;
2681         struct iface *iface;
2682
2683         iface = iface_lookup(port->bridge, iface_name);
2684         if (!iface) {
2685             iface = iface_create(port, cfg);
2686         } else {
2687             iface->cfg = cfg;
2688         }
2689
2690         /* Determine interface type.  The local port always has type
2691          * "internal".  Other ports take their type from the database and
2692          * default to "system" if none is specified. */
2693         iface->type = (!strcmp(iface_name, port->bridge->name) ? "internal"
2694                        : cfg->type[0] ? cfg->type
2695                        : "system");
2696     }
2697     shash_destroy(&new_ifaces);
2698 }
2699
2700 static void
2701 port_destroy(struct port *port)
2702 {
2703     if (port) {
2704         struct bridge *br = port->bridge;
2705         struct iface *iface, *next;
2706
2707         if (br->ofproto) {
2708             ofproto_bundle_unregister(br->ofproto, port);
2709         }
2710
2711         LIST_FOR_EACH_SAFE (iface, next, port_elem, &port->ifaces) {
2712             iface_destroy(iface);
2713         }
2714
2715         hmap_remove(&br->ports, &port->hmap_node);
2716
2717         VLOG_INFO("destroyed port %s on bridge %s", port->name, br->name);
2718
2719         free(port->name);
2720         free(port);
2721     }
2722 }
2723
2724 static struct port *
2725 port_lookup(const struct bridge *br, const char *name)
2726 {
2727     struct port *port;
2728
2729     HMAP_FOR_EACH_WITH_HASH (port, hmap_node, hash_string(name, 0),
2730                              &br->ports) {
2731         if (!strcmp(port->name, name)) {
2732             return port;
2733         }
2734     }
2735     return NULL;
2736 }
2737
2738 static bool
2739 enable_lacp(struct port *port, bool *activep)
2740 {
2741     if (!port->cfg->lacp) {
2742         /* XXX when LACP implementation has been sufficiently tested, enable by
2743          * default and make active on bonded ports. */
2744         return false;
2745     } else if (!strcmp(port->cfg->lacp, "off")) {
2746         return false;
2747     } else if (!strcmp(port->cfg->lacp, "active")) {
2748         *activep = true;
2749         return true;
2750     } else if (!strcmp(port->cfg->lacp, "passive")) {
2751         *activep = false;
2752         return true;
2753     } else {
2754         VLOG_WARN("port %s: unknown LACP mode %s",
2755                   port->name, port->cfg->lacp);
2756         return false;
2757     }
2758 }
2759
2760 static struct lacp_settings *
2761 port_configure_lacp(struct port *port, struct lacp_settings *s)
2762 {
2763     const char *lacp_time, *system_id;
2764     long long int custom_time;
2765     int priority;
2766
2767     if (!enable_lacp(port, &s->active)) {
2768         return NULL;
2769     }
2770
2771     s->name = port->name;
2772
2773     system_id = ovsrec_port_get_other_config_value(port->cfg, "lacp-system-id",
2774                                                    NULL);
2775     if (system_id) {
2776         if (sscanf(system_id, ETH_ADDR_SCAN_FMT,
2777                    ETH_ADDR_SCAN_ARGS(s->id)) != ETH_ADDR_SCAN_COUNT) {
2778             VLOG_WARN("port %s: LACP system ID (%s) must be an Ethernet"
2779                       " address.", port->name, system_id);
2780             return NULL;
2781         }
2782     } else {
2783         memcpy(s->id, port->bridge->ea, ETH_ADDR_LEN);
2784     }
2785
2786     if (eth_addr_is_zero(s->id)) {
2787         VLOG_WARN("port %s: Invalid zero LACP system ID.", port->name);
2788         return NULL;
2789     }
2790
2791     /* Prefer bondable links if unspecified. */
2792     priority = atoi(ovsrec_port_get_other_config_value(port->cfg,
2793                                                        "lacp-system-priority",
2794                                                        "0"));
2795     s->priority = (priority > 0 && priority <= UINT16_MAX
2796                    ? priority
2797                    : UINT16_MAX - !list_is_short(&port->ifaces));
2798
2799     s->heartbeat = !strcmp(ovsrec_port_get_other_config_value(port->cfg,
2800                                                               "lacp-heartbeat",
2801                                                               "false"),
2802                            "true");
2803
2804     lacp_time = ovsrec_port_get_other_config_value(port->cfg, "lacp-time",
2805                                                    "slow");
2806     custom_time = atoi(lacp_time);
2807     if (!strcmp(lacp_time, "fast")) {
2808         s->lacp_time = LACP_TIME_FAST;
2809     } else if (!strcmp(lacp_time, "slow")) {
2810         s->lacp_time = LACP_TIME_SLOW;
2811     } else if (custom_time > 0) {
2812         s->lacp_time = LACP_TIME_CUSTOM;
2813         s->custom_time = custom_time;
2814     } else {
2815         s->lacp_time = LACP_TIME_SLOW;
2816     }
2817
2818     return s;
2819 }
2820
2821 static void
2822 iface_configure_lacp(struct iface *iface, struct lacp_slave_settings *s)
2823 {
2824     int priority, portid, key;
2825
2826     portid = atoi(ovsrec_interface_get_other_config_value(iface->cfg,
2827                                                           "lacp-port-id",
2828                                                           "0"));
2829     priority =
2830         atoi(ovsrec_interface_get_other_config_value(iface->cfg,
2831                                                      "lacp-port-priority",
2832                                                      "0"));
2833     key = atoi(ovsrec_interface_get_other_config_value(iface->cfg,
2834                                                        "lacp-aggregation-key",
2835                                                        "0"));
2836
2837     if (portid <= 0 || portid > UINT16_MAX) {
2838         portid = iface->ofp_port;
2839     }
2840
2841     if (priority <= 0 || priority > UINT16_MAX) {
2842         priority = UINT16_MAX;
2843     }
2844
2845     if (key < 0 || key > UINT16_MAX) {
2846         key = 0;
2847     }
2848
2849     s->name = iface->name;
2850     s->id = portid;
2851     s->priority = priority;
2852     s->key = key;
2853 }
2854
2855 static void
2856 port_configure_bond(struct port *port, struct bond_settings *s,
2857                     uint32_t *bond_stable_ids)
2858 {
2859     const char *detect_s;
2860     struct iface *iface;
2861     int miimon_interval;
2862     size_t i;
2863
2864     s->name = port->name;
2865     s->balance = BM_AB;
2866     if (port->cfg->bond_mode) {
2867         if (!bond_mode_from_string(&s->balance, port->cfg->bond_mode)) {
2868             VLOG_WARN("port %s: unknown bond_mode %s, defaulting to %s",
2869                       port->name, port->cfg->bond_mode,
2870                       bond_mode_to_string(s->balance));
2871         }
2872     } else {
2873         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 1);
2874
2875         /* XXX: Post version 1.5.*, the default bond_mode changed from SLB to
2876          * active-backup. At some point we should remove this warning. */
2877         VLOG_WARN_RL(&rl, "port %s: Using the default bond_mode %s. Note that"
2878                      " in previous versions, the default bond_mode was"
2879                      " balance-slb", port->name,
2880                      bond_mode_to_string(s->balance));
2881     }
2882     if (s->balance == BM_SLB && port->bridge->cfg->n_flood_vlans) {
2883         VLOG_WARN("port %s: SLB bonds are incompatible with flood_vlans, "
2884                   "please use another bond type or disable flood_vlans",
2885                   port->name);
2886     }
2887
2888     miimon_interval =
2889         atoi(ovsrec_port_get_other_config_value(port->cfg,
2890                                                 "bond-miimon-interval", "0"));
2891     if (miimon_interval <= 0) {
2892         miimon_interval = 200;
2893     }
2894
2895     detect_s = ovsrec_port_get_other_config_value(port->cfg,
2896                                                   "bond-detect-mode",
2897                                                   "carrier");
2898     if (!strcmp(detect_s, "carrier")) {
2899         miimon_interval = 0;
2900     } else if (strcmp(detect_s, "miimon")) {
2901         VLOG_WARN("port %s: unsupported bond-detect-mode %s, "
2902                   "defaulting to carrier", port->name, detect_s);
2903         miimon_interval = 0;
2904     }
2905
2906     s->up_delay = MAX(0, port->cfg->bond_updelay);
2907     s->down_delay = MAX(0, port->cfg->bond_downdelay);
2908     s->basis = atoi(ovsrec_port_get_other_config_value(port->cfg,
2909                                                        "bond-hash-basis",
2910                                                        "0"));
2911     s->rebalance_interval = atoi(
2912         ovsrec_port_get_other_config_value(port->cfg,
2913                                            "bond-rebalance-interval",
2914                                            "10000"));
2915     if (s->rebalance_interval && s->rebalance_interval < 1000) {
2916         s->rebalance_interval = 1000;
2917     }
2918
2919     s->fake_iface = port->cfg->bond_fake_iface;
2920
2921     i = 0;
2922     LIST_FOR_EACH (iface, port_elem, &port->ifaces) {
2923         long long stable_id;
2924
2925         stable_id =
2926             atoll(ovsrec_interface_get_other_config_value(iface->cfg,
2927                                                           "bond-stable-id",
2928                                                           "0"));
2929         if (stable_id <= 0 || stable_id >= UINT32_MAX) {
2930             stable_id = iface->ofp_port;
2931         }
2932         bond_stable_ids[i++] = stable_id;
2933
2934         netdev_set_miimon_interval(iface->netdev, miimon_interval);
2935     }
2936 }
2937
2938 /* Returns true if 'port' is synthetic, that is, if we constructed it locally
2939  * instead of obtaining it from the database. */
2940 static bool
2941 port_is_synthetic(const struct port *port)
2942 {
2943     return ovsdb_idl_row_is_synthetic(&port->cfg->header_);
2944 }
2945 \f
2946 /* Interface functions. */
2947
2948 static struct iface *
2949 iface_create(struct port *port, const struct ovsrec_interface *if_cfg)
2950 {
2951     struct bridge *br = port->bridge;
2952     struct iface *iface;
2953     char *name = if_cfg->name;
2954
2955     iface = xzalloc(sizeof *iface);
2956     iface->port = port;
2957     iface->name = xstrdup(name);
2958     iface->ofp_port = -1;
2959     iface->tag = tag_create_random();
2960     iface->netdev = NULL;
2961     iface->cfg = if_cfg;
2962     iface->need_refresh = true;
2963
2964     hmap_insert(&br->iface_by_name, &iface->name_node, hash_string(name, 0));
2965
2966     list_push_back(&port->ifaces, &iface->port_elem);
2967
2968     VLOG_DBG("attached network device %s to port %s", iface->name, port->name);
2969
2970     return iface;
2971 }
2972
2973 static void
2974 iface_destroy(struct iface *iface)
2975 {
2976     if (iface) {
2977         struct port *port = iface->port;
2978         struct bridge *br = port->bridge;
2979
2980         if (br->ofproto && iface->ofp_port >= 0) {
2981             ofproto_port_unregister(br->ofproto, iface->ofp_port);
2982         }
2983
2984         if (iface->ofp_port >= 0) {
2985             hmap_remove(&br->ifaces, &iface->ofp_port_node);
2986         }
2987
2988         list_remove(&iface->port_elem);
2989         hmap_remove(&br->iface_by_name, &iface->name_node);
2990
2991         netdev_close(iface->netdev);
2992
2993         free(iface->name);
2994         free(iface);
2995     }
2996 }
2997
2998 static struct iface *
2999 iface_lookup(const struct bridge *br, const char *name)
3000 {
3001     struct iface *iface;
3002
3003     HMAP_FOR_EACH_WITH_HASH (iface, name_node, hash_string(name, 0),
3004                              &br->iface_by_name) {
3005         if (!strcmp(iface->name, name)) {
3006             return iface;
3007         }
3008     }
3009
3010     return NULL;
3011 }
3012
3013 static struct iface *
3014 iface_find(const char *name)
3015 {
3016     const struct bridge *br;
3017
3018     HMAP_FOR_EACH (br, node, &all_bridges) {
3019         struct iface *iface = iface_lookup(br, name);
3020
3021         if (iface) {
3022             return iface;
3023         }
3024     }
3025     return NULL;
3026 }
3027
3028 static struct iface *
3029 iface_from_ofp_port(const struct bridge *br, uint16_t ofp_port)
3030 {
3031     struct iface *iface;
3032
3033     HMAP_FOR_EACH_IN_BUCKET (iface, ofp_port_node,
3034                              hash_int(ofp_port, 0), &br->ifaces) {
3035         if (iface->ofp_port == ofp_port) {
3036             return iface;
3037         }
3038     }
3039     return NULL;
3040 }
3041
3042 /* Set Ethernet address of 'iface', if one is specified in the configuration
3043  * file. */
3044 static void
3045 iface_set_mac(struct iface *iface)
3046 {
3047     uint8_t ea[ETH_ADDR_LEN];
3048
3049     if (!strcmp(iface->type, "internal")
3050         && iface->cfg->mac && eth_addr_from_string(iface->cfg->mac, ea)) {
3051         if (iface->ofp_port == OFPP_LOCAL) {
3052             VLOG_ERR("interface %s: ignoring mac in Interface record "
3053                      "(use Bridge record to set local port's mac)",
3054                      iface->name);
3055         } else if (eth_addr_is_multicast(ea)) {
3056             VLOG_ERR("interface %s: cannot set MAC to multicast address",
3057                      iface->name);
3058         } else {
3059             int error = netdev_set_etheraddr(iface->netdev, ea);
3060             if (error) {
3061                 VLOG_ERR("interface %s: setting MAC failed (%s)",
3062                          iface->name, strerror(error));
3063             }
3064         }
3065     }
3066 }
3067
3068 /* Sets the ofport column of 'if_cfg' to 'ofport'. */
3069 static void
3070 iface_set_ofport(const struct ovsrec_interface *if_cfg, int64_t ofport)
3071 {
3072     if (if_cfg && !ovsdb_idl_row_is_synthetic(&if_cfg->header_)) {
3073         ovsrec_interface_set_ofport(if_cfg, &ofport, 1);
3074     }
3075 }
3076
3077 /* Clears all of the fields in 'if_cfg' that indicate interface status, and
3078  * sets the "ofport" field to -1.
3079  *
3080  * This is appropriate when 'if_cfg''s interface cannot be created or is
3081  * otherwise invalid. */
3082 static void
3083 iface_clear_db_record(const struct ovsrec_interface *if_cfg)
3084 {
3085     if (!ovsdb_idl_row_is_synthetic(&if_cfg->header_)) {
3086         iface_set_ofport(if_cfg, -1);
3087         ovsrec_interface_set_status(if_cfg, NULL, NULL, 0);
3088         ovsrec_interface_set_admin_state(if_cfg, NULL);
3089         ovsrec_interface_set_duplex(if_cfg, NULL);
3090         ovsrec_interface_set_link_speed(if_cfg, NULL, 0);
3091         ovsrec_interface_set_link_state(if_cfg, NULL);
3092         ovsrec_interface_set_mtu(if_cfg, NULL, 0);
3093         ovsrec_interface_set_cfm_fault(if_cfg, NULL, 0);
3094         ovsrec_interface_set_cfm_fault_status(if_cfg, NULL, 0);
3095         ovsrec_interface_set_cfm_remote_mpids(if_cfg, NULL, 0);
3096         ovsrec_interface_set_lacp_current(if_cfg, NULL, 0);
3097         ovsrec_interface_set_statistics(if_cfg, NULL, NULL, 0);
3098     }
3099 }
3100
3101 /* Adds the 'n' key-value pairs in 'keys' in 'values' to 'shash'.
3102  *
3103  * The value strings in '*shash' are taken directly from values[], not copied,
3104  * so the caller should not modify or free them. */
3105 static void
3106 shash_from_ovs_idl_map(char **keys, char **values, size_t n,
3107                        struct shash *shash)
3108 {
3109     size_t i;
3110
3111     shash_init(shash);
3112     for (i = 0; i < n; i++) {
3113         shash_add(shash, keys[i], values[i]);
3114     }
3115 }
3116
3117 /* Creates 'keys' and 'values' arrays from 'shash'.
3118  *
3119  * Sets 'keys' and 'values' to heap allocated arrays representing the key-value
3120  * pairs in 'shash'.  The caller takes ownership of 'keys' and 'values'.  They
3121  * are populated with with strings taken directly from 'shash' and thus have
3122  * the same ownership of the key-value pairs in shash.
3123  */
3124 static void
3125 shash_to_ovs_idl_map(struct shash *shash,
3126                      char ***keys, char ***values, size_t *n)
3127 {
3128     size_t i, count;
3129     char **k, **v;
3130     struct shash_node *sn;
3131
3132     count = shash_count(shash);
3133
3134     k = xmalloc(count * sizeof *k);
3135     v = xmalloc(count * sizeof *v);
3136
3137     i = 0;
3138     SHASH_FOR_EACH(sn, shash) {
3139         k[i] = sn->name;
3140         v[i] = sn->data;
3141         i++;
3142     }
3143
3144     *n      = count;
3145     *keys   = k;
3146     *values = v;
3147 }
3148
3149 struct iface_delete_queues_cbdata {
3150     struct netdev *netdev;
3151     const struct ovsdb_datum *queues;
3152 };
3153
3154 static bool
3155 queue_ids_include(const struct ovsdb_datum *queues, int64_t target)
3156 {
3157     union ovsdb_atom atom;
3158
3159     atom.integer = target;
3160     return ovsdb_datum_find_key(queues, &atom, OVSDB_TYPE_INTEGER) != UINT_MAX;
3161 }
3162
3163 static void
3164 iface_delete_queues(unsigned int queue_id,
3165                     const struct shash *details OVS_UNUSED, void *cbdata_)
3166 {
3167     struct iface_delete_queues_cbdata *cbdata = cbdata_;
3168
3169     if (!queue_ids_include(cbdata->queues, queue_id)) {
3170         netdev_delete_queue(cbdata->netdev, queue_id);
3171     }
3172 }
3173
3174 static void
3175 iface_configure_qos(struct iface *iface, const struct ovsrec_qos *qos)
3176 {
3177     struct ofpbuf queues_buf;
3178
3179     ofpbuf_init(&queues_buf, 0);
3180
3181     if (!qos || qos->type[0] == '\0' || qos->n_queues < 1) {
3182         netdev_set_qos(iface->netdev, NULL, NULL);
3183     } else {
3184         struct iface_delete_queues_cbdata cbdata;
3185         struct shash details;
3186         bool queue_zero;
3187         size_t i;
3188
3189         /* Configure top-level Qos for 'iface'. */
3190         shash_from_ovs_idl_map(qos->key_other_config, qos->value_other_config,
3191                                qos->n_other_config, &details);
3192         netdev_set_qos(iface->netdev, qos->type, &details);
3193         shash_destroy(&details);
3194
3195         /* Deconfigure queues that were deleted. */
3196         cbdata.netdev = iface->netdev;
3197         cbdata.queues = ovsrec_qos_get_queues(qos, OVSDB_TYPE_INTEGER,
3198                                               OVSDB_TYPE_UUID);
3199         netdev_dump_queues(iface->netdev, iface_delete_queues, &cbdata);
3200
3201         /* Configure queues for 'iface'. */
3202         queue_zero = false;
3203         for (i = 0; i < qos->n_queues; i++) {
3204             const struct ovsrec_queue *queue = qos->value_queues[i];
3205             unsigned int queue_id = qos->key_queues[i];
3206
3207             if (queue_id == 0) {
3208                 queue_zero = true;
3209             }
3210
3211             if (queue->n_dscp == 1) {
3212                 struct ofproto_port_queue *port_queue;
3213
3214                 port_queue = ofpbuf_put_uninit(&queues_buf,
3215                                                sizeof *port_queue);
3216                 port_queue->queue = queue_id;
3217                 port_queue->dscp = queue->dscp[0];
3218             }
3219
3220             shash_from_ovs_idl_map(queue->key_other_config,
3221                                    queue->value_other_config,
3222                                    queue->n_other_config, &details);
3223             netdev_set_queue(iface->netdev, queue_id, &details);
3224             shash_destroy(&details);
3225         }
3226         if (!queue_zero) {
3227             shash_init(&details);
3228             netdev_set_queue(iface->netdev, 0, &details);
3229             shash_destroy(&details);
3230         }
3231     }
3232
3233     if (iface->ofp_port >= 0) {
3234         const struct ofproto_port_queue *port_queues = queues_buf.data;
3235         size_t n_queues = queues_buf.size / sizeof *port_queues;
3236
3237         ofproto_port_set_queues(iface->port->bridge->ofproto, iface->ofp_port,
3238                                 port_queues, n_queues);
3239     }
3240
3241     netdev_set_policing(iface->netdev,
3242                         iface->cfg->ingress_policing_rate,
3243                         iface->cfg->ingress_policing_burst);
3244
3245     ofpbuf_uninit(&queues_buf);
3246 }
3247
3248 static void
3249 iface_configure_cfm(struct iface *iface)
3250 {
3251     const struct ovsrec_interface *cfg = iface->cfg;
3252     const char *extended_str, *opstate_str;
3253     const char *cfm_ccm_vlan;
3254     struct cfm_settings s;
3255
3256     if (!cfg->n_cfm_mpid) {
3257         ofproto_port_clear_cfm(iface->port->bridge->ofproto, iface->ofp_port);
3258         return;
3259     }
3260
3261     s.mpid = *cfg->cfm_mpid;
3262     s.interval = atoi(ovsrec_interface_get_other_config_value(iface->cfg,
3263                                                               "cfm_interval",
3264                                                               "0"));
3265     cfm_ccm_vlan = ovsrec_interface_get_other_config_value(iface->cfg,
3266                                                            "cfm_ccm_vlan",
3267                                                            "0");
3268     s.ccm_pcp = atoi(ovsrec_interface_get_other_config_value(iface->cfg,
3269                                                              "cfm_ccm_pcp",
3270                                                              "0"));
3271     if (s.interval <= 0) {
3272         s.interval = 1000;
3273     }
3274
3275     if (!strcasecmp("random", cfm_ccm_vlan)) {
3276         s.ccm_vlan = CFM_RANDOM_VLAN;
3277     } else {
3278         s.ccm_vlan = atoi(cfm_ccm_vlan);
3279         if (s.ccm_vlan == CFM_RANDOM_VLAN) {
3280             s.ccm_vlan = 0;
3281         }
3282     }
3283
3284     extended_str = ovsrec_interface_get_other_config_value(iface->cfg,
3285                                                            "cfm_extended",
3286                                                            "false");
3287     s.extended = !strcasecmp("true", extended_str);
3288
3289     opstate_str = ovsrec_interface_get_other_config_value(iface->cfg,
3290                                                           "cfm_opstate",
3291                                                           "up");
3292     s.opup = !strcasecmp("up", opstate_str);
3293
3294     ofproto_port_set_cfm(iface->port->bridge->ofproto, iface->ofp_port, &s);
3295 }
3296
3297 /* Returns true if 'iface' is synthetic, that is, if we constructed it locally
3298  * instead of obtaining it from the database. */
3299 static bool
3300 iface_is_synthetic(const struct iface *iface)
3301 {
3302     return ovsdb_idl_row_is_synthetic(&iface->cfg->header_);
3303 }
3304
3305 \f
3306 /* Port mirroring. */
3307
3308 static struct mirror *
3309 mirror_find_by_uuid(struct bridge *br, const struct uuid *uuid)
3310 {
3311     struct mirror *m;
3312
3313     HMAP_FOR_EACH_IN_BUCKET (m, hmap_node, uuid_hash(uuid), &br->mirrors) {
3314         if (uuid_equals(uuid, &m->uuid)) {
3315             return m;
3316         }
3317     }
3318     return NULL;
3319 }
3320
3321 static void
3322 bridge_configure_mirrors(struct bridge *br)
3323 {
3324     const struct ovsdb_datum *mc;
3325     unsigned long *flood_vlans;
3326     struct mirror *m, *next;
3327     size_t i;
3328
3329     /* Get rid of deleted mirrors. */
3330     mc = ovsrec_bridge_get_mirrors(br->cfg, OVSDB_TYPE_UUID);
3331     HMAP_FOR_EACH_SAFE (m, next, hmap_node, &br->mirrors) {
3332         union ovsdb_atom atom;
3333
3334         atom.uuid = m->uuid;
3335         if (ovsdb_datum_find_key(mc, &atom, OVSDB_TYPE_UUID) == UINT_MAX) {
3336             mirror_destroy(m);
3337         }
3338     }
3339
3340     /* Add new mirrors and reconfigure existing ones. */
3341     for (i = 0; i < br->cfg->n_mirrors; i++) {
3342         const struct ovsrec_mirror *cfg = br->cfg->mirrors[i];
3343         struct mirror *m = mirror_find_by_uuid(br, &cfg->header_.uuid);
3344         if (!m) {
3345             m = mirror_create(br, cfg);
3346         }
3347         m->cfg = cfg;
3348         if (!mirror_configure(m)) {
3349             mirror_destroy(m);
3350         }
3351     }
3352
3353     /* Update flooded vlans (for RSPAN). */
3354     flood_vlans = vlan_bitmap_from_array(br->cfg->flood_vlans,
3355                                          br->cfg->n_flood_vlans);
3356     ofproto_set_flood_vlans(br->ofproto, flood_vlans);
3357     bitmap_free(flood_vlans);
3358 }
3359
3360 static struct mirror *
3361 mirror_create(struct bridge *br, const struct ovsrec_mirror *cfg)
3362 {
3363     struct mirror *m;
3364
3365     m = xzalloc(sizeof *m);
3366     m->uuid = cfg->header_.uuid;
3367     hmap_insert(&br->mirrors, &m->hmap_node, uuid_hash(&m->uuid));
3368     m->bridge = br;
3369     m->name = xstrdup(cfg->name);
3370
3371     return m;
3372 }
3373
3374 static void
3375 mirror_destroy(struct mirror *m)
3376 {
3377     if (m) {
3378         struct bridge *br = m->bridge;
3379
3380         if (br->ofproto) {
3381             ofproto_mirror_unregister(br->ofproto, m);
3382         }
3383
3384         hmap_remove(&br->mirrors, &m->hmap_node);
3385         free(m->name);
3386         free(m);
3387     }
3388 }
3389
3390 static void
3391 mirror_collect_ports(struct mirror *m,
3392                      struct ovsrec_port **in_ports, int n_in_ports,
3393                      void ***out_portsp, size_t *n_out_portsp)
3394 {
3395     void **out_ports = xmalloc(n_in_ports * sizeof *out_ports);
3396     size_t n_out_ports = 0;
3397     size_t i;
3398
3399     for (i = 0; i < n_in_ports; i++) {
3400         const char *name = in_ports[i]->name;
3401         struct port *port = port_lookup(m->bridge, name);
3402         if (port) {
3403             out_ports[n_out_ports++] = port;
3404         } else {
3405             VLOG_WARN("bridge %s: mirror %s cannot match on nonexistent "
3406                       "port %s", m->bridge->name, m->name, name);
3407         }
3408     }
3409     *out_portsp = out_ports;
3410     *n_out_portsp = n_out_ports;
3411 }
3412
3413 static bool
3414 mirror_configure(struct mirror *m)
3415 {
3416     const struct ovsrec_mirror *cfg = m->cfg;
3417     struct ofproto_mirror_settings s;
3418
3419     /* Set name. */
3420     if (strcmp(cfg->name, m->name)) {
3421         free(m->name);
3422         m->name = xstrdup(cfg->name);
3423     }
3424     s.name = m->name;
3425
3426     /* Get output port or VLAN. */
3427     if (cfg->output_port) {
3428         s.out_bundle = port_lookup(m->bridge, cfg->output_port->name);
3429         if (!s.out_bundle) {
3430             VLOG_ERR("bridge %s: mirror %s outputs to port not on bridge",
3431                      m->bridge->name, m->name);
3432             return false;
3433         }
3434         s.out_vlan = UINT16_MAX;
3435
3436         if (cfg->output_vlan) {
3437             VLOG_ERR("bridge %s: mirror %s specifies both output port and "
3438                      "output vlan; ignoring output vlan",
3439                      m->bridge->name, m->name);
3440         }
3441     } else if (cfg->output_vlan) {
3442         /* The database should prevent invalid VLAN values. */
3443         s.out_bundle = NULL;
3444         s.out_vlan = *cfg->output_vlan;
3445     } else {
3446         VLOG_ERR("bridge %s: mirror %s does not specify output; ignoring",
3447                  m->bridge->name, m->name);
3448         return false;
3449     }
3450
3451     /* Get port selection. */
3452     if (cfg->select_all) {
3453         size_t n_ports = hmap_count(&m->bridge->ports);
3454         void **ports = xmalloc(n_ports * sizeof *ports);
3455         struct port *port;
3456         size_t i;
3457
3458         i = 0;
3459         HMAP_FOR_EACH (port, hmap_node, &m->bridge->ports) {
3460             ports[i++] = port;
3461         }
3462
3463         s.srcs = ports;
3464         s.n_srcs = n_ports;
3465
3466         s.dsts = ports;
3467         s.n_dsts = n_ports;
3468     } else {
3469         /* Get ports, dropping ports that don't exist.
3470          * The IDL ensures that there are no duplicates. */
3471         mirror_collect_ports(m, cfg->select_src_port, cfg->n_select_src_port,
3472                              &s.srcs, &s.n_srcs);
3473         mirror_collect_ports(m, cfg->select_dst_port, cfg->n_select_dst_port,
3474                              &s.dsts, &s.n_dsts);
3475     }
3476
3477     /* Get VLAN selection. */
3478     s.src_vlans = vlan_bitmap_from_array(cfg->select_vlan, cfg->n_select_vlan);
3479
3480     /* Configure. */
3481     ofproto_mirror_register(m->bridge->ofproto, m, &s);
3482
3483     /* Clean up. */
3484     if (s.srcs != s.dsts) {
3485         free(s.dsts);
3486     }
3487     free(s.srcs);
3488     free(s.src_vlans);
3489
3490     return true;
3491 }
3492 \f
3493 /* Linux VLAN device support (e.g. "eth0.10" for VLAN 10.)
3494  *
3495  * This is deprecated.  It is only for compatibility with broken device drivers
3496  * in old versions of Linux that do not properly support VLANs when VLAN
3497  * devices are not used.  When broken device drivers are no longer in
3498  * widespread use, we will delete these interfaces. */
3499
3500 static void **blocks;
3501 static size_t n_blocks, allocated_blocks;
3502
3503 /* Adds 'block' to a list of blocks that have to be freed with free() when the
3504  * VLAN splinters are reconfigured. */
3505 static void
3506 register_block(void *block)
3507 {
3508     if (n_blocks >= allocated_blocks) {
3509         blocks = x2nrealloc(blocks, &allocated_blocks, sizeof *blocks);
3510     }
3511     blocks[n_blocks++] = block;
3512 }
3513
3514 /* Frees all of the blocks registered with register_block(). */
3515 static void
3516 free_registered_blocks(void)
3517 {
3518     size_t i;
3519
3520     for (i = 0; i < n_blocks; i++) {
3521         free(blocks[i]);
3522     }
3523     n_blocks = 0;
3524 }
3525
3526 /* Returns true if VLAN splinters are enabled on 'iface_cfg', false
3527  * otherwise. */
3528 static bool
3529 vlan_splinters_is_enabled(const struct ovsrec_interface *iface_cfg)
3530 {
3531     const char *value;
3532
3533     value = ovsrec_interface_get_other_config_value(iface_cfg,
3534                                                     "enable-vlan-splinters",
3535                                                     "");
3536     return !strcmp(value, "true");
3537 }
3538
3539 /* Figures out the set of VLANs that are in use for the purpose of VLAN
3540  * splinters.
3541  *
3542  * If VLAN splinters are enabled on at least one interface and any VLANs are in
3543  * use, returns a 4096-bit bitmap with a 1-bit for each in-use VLAN (bits 0 and
3544  * 4095 will not be set).  The caller is responsible for freeing the bitmap,
3545  * with free().
3546  *
3547  * If VLANs splinters are not enabled on any interface or if no VLANs are in
3548  * use, returns NULL.
3549  *
3550  * Updates 'vlan_splinters_enabled_anywhere'. */
3551 static unsigned long int *
3552 collect_splinter_vlans(const struct ovsrec_open_vswitch *ovs_cfg)
3553 {
3554     unsigned long int *splinter_vlans;
3555     struct sset splinter_ifaces;
3556     const char *real_dev_name;
3557     struct shash *real_devs;
3558     struct shash_node *node;
3559     struct bridge *br;
3560     size_t i;
3561
3562     /* Free space allocated for synthesized ports and interfaces, since we're
3563      * in the process of reconstructing all of them. */
3564     free_registered_blocks();
3565
3566     splinter_vlans = bitmap_allocate(4096);
3567     sset_init(&splinter_ifaces);
3568     vlan_splinters_enabled_anywhere = false;
3569     for (i = 0; i < ovs_cfg->n_bridges; i++) {
3570         struct ovsrec_bridge *br_cfg = ovs_cfg->bridges[i];
3571         size_t j;
3572
3573         for (j = 0; j < br_cfg->n_ports; j++) {
3574             struct ovsrec_port *port_cfg = br_cfg->ports[j];
3575             int k;
3576
3577             for (k = 0; k < port_cfg->n_interfaces; k++) {
3578                 struct ovsrec_interface *iface_cfg = port_cfg->interfaces[k];
3579
3580                 if (vlan_splinters_is_enabled(iface_cfg)) {
3581                     vlan_splinters_enabled_anywhere = true;
3582                     sset_add(&splinter_ifaces, iface_cfg->name);
3583                     vlan_bitmap_from_array__(port_cfg->trunks,
3584                                              port_cfg->n_trunks,
3585                                              splinter_vlans);
3586                 }
3587             }
3588
3589             if (port_cfg->tag && *port_cfg->tag > 0 && *port_cfg->tag < 4095) {
3590                 bitmap_set1(splinter_vlans, *port_cfg->tag);
3591             }
3592         }
3593     }
3594
3595     if (!vlan_splinters_enabled_anywhere) {
3596         free(splinter_vlans);
3597         sset_destroy(&splinter_ifaces);
3598         return NULL;
3599     }
3600
3601     HMAP_FOR_EACH (br, node, &all_bridges) {
3602         if (br->ofproto) {
3603             ofproto_get_vlan_usage(br->ofproto, splinter_vlans);
3604         }
3605     }
3606
3607     /* Don't allow VLANs 0 or 4095 to be splintered.  VLAN 0 should appear on
3608      * the real device.  VLAN 4095 is reserved and Linux doesn't allow a VLAN
3609      * device to be created for it. */
3610     bitmap_set0(splinter_vlans, 0);
3611     bitmap_set0(splinter_vlans, 4095);
3612
3613     /* Delete all VLAN devices that we don't need. */
3614     vlandev_refresh();
3615     real_devs = vlandev_get_real_devs();
3616     SHASH_FOR_EACH (node, real_devs) {
3617         const struct vlan_real_dev *real_dev = node->data;
3618         const struct vlan_dev *vlan_dev;
3619         bool real_dev_has_splinters;
3620
3621         real_dev_has_splinters = sset_contains(&splinter_ifaces,
3622                                                real_dev->name);
3623         HMAP_FOR_EACH (vlan_dev, hmap_node, &real_dev->vlan_devs) {
3624             if (!real_dev_has_splinters
3625                 || !bitmap_is_set(splinter_vlans, vlan_dev->vid)) {
3626                 struct netdev *netdev;
3627
3628                 if (!netdev_open(vlan_dev->name, "system", &netdev)) {
3629                     if (!netdev_get_in4(netdev, NULL, NULL) ||
3630                         !netdev_get_in6(netdev, NULL)) {
3631                         vlandev_del(vlan_dev->name);
3632                     } else {
3633                         /* It has an IP address configured, so we don't own
3634                          * it.  Don't delete it. */
3635                     }
3636                     netdev_close(netdev);
3637                 }
3638             }
3639
3640         }
3641     }
3642
3643     /* Add all VLAN devices that we need. */
3644     SSET_FOR_EACH (real_dev_name, &splinter_ifaces) {
3645         int vid;
3646
3647         BITMAP_FOR_EACH_1 (vid, 4096, splinter_vlans) {
3648             if (!vlandev_get_name(real_dev_name, vid)) {
3649                 vlandev_add(real_dev_name, vid);
3650             }
3651         }
3652     }
3653
3654     vlandev_refresh();
3655
3656     sset_destroy(&splinter_ifaces);
3657
3658     if (bitmap_scan(splinter_vlans, 0, 4096) >= 4096) {
3659         free(splinter_vlans);
3660         return NULL;
3661     }
3662     return splinter_vlans;
3663 }
3664
3665 /* Pushes the configure of VLAN splinter port 'port' (e.g. eth0.9) down to
3666  * ofproto.  */
3667 static void
3668 configure_splinter_port(struct port *port)
3669 {
3670     struct ofproto *ofproto = port->bridge->ofproto;
3671     uint16_t realdev_ofp_port;
3672     const char *realdev_name;
3673     struct iface *vlandev, *realdev;
3674
3675     ofproto_bundle_unregister(port->bridge->ofproto, port);
3676
3677     vlandev = CONTAINER_OF(list_front(&port->ifaces), struct iface,
3678                            port_elem);
3679
3680     realdev_name = ovsrec_port_get_other_config_value(port->cfg,
3681                                                       "realdev", NULL);
3682     realdev = iface_lookup(port->bridge, realdev_name);
3683     realdev_ofp_port = realdev ? realdev->ofp_port : 0;
3684
3685     ofproto_port_set_realdev(ofproto, vlandev->ofp_port, realdev_ofp_port,
3686                              *port->cfg->tag);
3687 }
3688
3689 static struct ovsrec_port *
3690 synthesize_splinter_port(const char *real_dev_name,
3691                          const char *vlan_dev_name, int vid)
3692 {
3693     struct ovsrec_interface *iface;
3694     struct ovsrec_port *port;
3695
3696     iface = xzalloc(sizeof *iface);
3697     iface->name = xstrdup(vlan_dev_name);
3698     iface->type = "system";
3699
3700     port = xzalloc(sizeof *port);
3701     port->interfaces = xmemdup(&iface, sizeof iface);
3702     port->n_interfaces = 1;
3703     port->name = xstrdup(vlan_dev_name);
3704     port->vlan_mode = "splinter";
3705     port->tag = xmalloc(sizeof *port->tag);
3706     *port->tag = vid;
3707     port->key_other_config = xmalloc(sizeof *port->key_other_config);
3708     port->key_other_config[0] = "realdev";
3709     port->value_other_config = xmalloc(sizeof *port->value_other_config);
3710     port->value_other_config[0] = xstrdup(real_dev_name);
3711     port->n_other_config = 1;
3712
3713     register_block(iface);
3714     register_block(iface->name);
3715     register_block(port);
3716     register_block(port->interfaces);
3717     register_block(port->name);
3718     register_block(port->tag);
3719     register_block(port->key_other_config);
3720     register_block(port->value_other_config);
3721     register_block(port->value_other_config[0]);
3722
3723     return port;
3724 }
3725
3726 /* For each interface with 'br' that has VLAN splinters enabled, adds a
3727  * corresponding ovsrec_port to 'ports' for each splinter VLAN marked with a
3728  * 1-bit in the 'splinter_vlans' bitmap. */
3729 static void
3730 add_vlan_splinter_ports(struct bridge *br,
3731                         const unsigned long int *splinter_vlans,
3732                         struct shash *ports)
3733 {
3734     size_t i;
3735
3736     /* We iterate through 'br->cfg->ports' instead of 'ports' here because
3737      * we're modifying 'ports'. */
3738     for (i = 0; i < br->cfg->n_ports; i++) {
3739         const char *name = br->cfg->ports[i]->name;
3740         struct ovsrec_port *port_cfg = shash_find_data(ports, name);
3741         size_t j;
3742
3743         for (j = 0; j < port_cfg->n_interfaces; j++) {
3744             struct ovsrec_interface *iface_cfg = port_cfg->interfaces[j];
3745
3746             if (vlan_splinters_is_enabled(iface_cfg)) {
3747                 const char *real_dev_name;
3748                 uint16_t vid;
3749
3750                 real_dev_name = iface_cfg->name;
3751                 BITMAP_FOR_EACH_1 (vid, 4096, splinter_vlans) {
3752                     const char *vlan_dev_name;
3753
3754                     vlan_dev_name = vlandev_get_name(real_dev_name, vid);
3755                     if (vlan_dev_name
3756                         && !shash_find(ports, vlan_dev_name)) {
3757                         shash_add(ports, vlan_dev_name,
3758                                   synthesize_splinter_port(
3759                                       real_dev_name, vlan_dev_name, vid));
3760                     }
3761                 }
3762             }
3763         }
3764     }
3765 }
3766
3767 static void
3768 mirror_refresh_stats(struct mirror *m)
3769 {
3770     struct ofproto *ofproto = m->bridge->ofproto;
3771     uint64_t tx_packets, tx_bytes;
3772     char *keys[2];
3773     int64_t values[2];
3774     size_t stat_cnt = 0;
3775
3776     if (ofproto_mirror_get_stats(ofproto, m, &tx_packets, &tx_bytes)) {
3777         ovsrec_mirror_set_statistics(m->cfg, NULL, NULL, 0);
3778         return;
3779     }
3780
3781     if (tx_packets != UINT64_MAX) {
3782         keys[stat_cnt] = "tx_packets";
3783         values[stat_cnt] = tx_packets;
3784         stat_cnt++;
3785     }
3786     if (tx_bytes != UINT64_MAX) {
3787         keys[stat_cnt] = "tx_bytes";
3788         values[stat_cnt] = tx_bytes;
3789         stat_cnt++;
3790     }
3791
3792     ovsrec_mirror_set_statistics(m->cfg, keys, values, stat_cnt);
3793 }