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