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