ofproto: Improve abstraction by using OpenFlow port numbers in interface.
[sliver-openvswitch.git] / vswitchd / bridge.c
1 /* Copyright (c) 2008, 2009, 2010, 2011 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 "byte-order.h"
19 #include <assert.h>
20 #include <errno.h>
21 #include <arpa/inet.h>
22 #include <ctype.h>
23 #include <inttypes.h>
24 #include <sys/socket.h>
25 #include <net/if.h>
26 #include <openflow/openflow.h>
27 #include <signal.h>
28 #include <stdlib.h>
29 #include <strings.h>
30 #include <sys/stat.h>
31 #include <sys/socket.h>
32 #include <sys/types.h>
33 #include <unistd.h>
34 #include "bitmap.h"
35 #include "bond.h"
36 #include "cfm.h"
37 #include "classifier.h"
38 #include "coverage.h"
39 #include "daemon.h"
40 #include "dirs.h"
41 #include "dpif.h"
42 #include "dynamic-string.h"
43 #include "flow.h"
44 #include "hash.h"
45 #include "hmap.h"
46 #include "jsonrpc.h"
47 #include "lacp.h"
48 #include "list.h"
49 #include "mac-learning.h"
50 #include "netdev.h"
51 #include "netlink.h"
52 #include "odp-util.h"
53 #include "ofp-print.h"
54 #include "ofpbuf.h"
55 #include "ofproto/netflow.h"
56 #include "ofproto/ofproto.h"
57 #include "ovsdb-data.h"
58 #include "packets.h"
59 #include "poll-loop.h"
60 #include "process.h"
61 #include "sha1.h"
62 #include "shash.h"
63 #include "socket-util.h"
64 #include "stream-ssl.h"
65 #include "sset.h"
66 #include "svec.h"
67 #include "system-stats.h"
68 #include "timeval.h"
69 #include "util.h"
70 #include "unixctl.h"
71 #include "vconn.h"
72 #include "vswitchd/vswitch-idl.h"
73 #include "xenserver.h"
74 #include "vlog.h"
75 #include "sflow_api.h"
76 #include "vlan-bitmap.h"
77
78 VLOG_DEFINE_THIS_MODULE(bridge);
79
80 COVERAGE_DEFINE(bridge_reconfigure);
81
82 struct iface {
83     /* These members are always valid. */
84     struct list port_elem;      /* Element in struct port's "ifaces" list. */
85     struct hmap_node name_node; /* In struct bridge's "iface_by_name" hmap. */
86     struct port *port;          /* Containing port. */
87     char *name;                 /* Host network device name. */
88     tag_type tag;               /* Tag associated with this interface. */
89
90     /* These members are valid only after bridge_reconfigure() causes them to
91      * be initialized. */
92     struct hmap_node ofp_port_node; /* In struct bridge's "ifaces" hmap. */
93     int ofp_port;               /* OpenFlow port number, -1 if unknown. */
94     struct netdev *netdev;      /* Network device. */
95     const char *type;           /* Usually same as cfg->type. */
96     const struct ovsrec_interface *cfg;
97 };
98
99 struct mirror {
100     struct uuid uuid;           /* UUID of this "mirror" record in database. */
101     struct hmap_node hmap_node; /* In struct bridge's "mirrors" hmap. */
102     struct bridge *bridge;
103     char *name;
104 };
105
106 struct port {
107     struct bridge *bridge;
108     struct hmap_node hmap_node; /* Element in struct bridge's "ports" hmap. */
109     char *name;
110
111     const struct ovsrec_port *cfg;
112
113     /* An ordinary bridge port has 1 interface.
114      * A bridge port for bonding has at least 2 interfaces. */
115     struct list ifaces;         /* List of "struct iface"s. */
116 };
117
118 struct bridge {
119     struct hmap_node node;      /* In 'all_bridges'. */
120     char *name;                 /* User-specified arbitrary name. */
121     char *type;                 /* Datapath type. */
122     uint8_t ea[ETH_ADDR_LEN];   /* Bridge Ethernet Address. */
123     uint8_t default_ea[ETH_ADDR_LEN]; /* Default MAC. */
124     const struct ovsrec_bridge *cfg;
125
126     /* OpenFlow switch processing. */
127     struct ofproto *ofproto;    /* OpenFlow switch. */
128
129     /* Bridge ports. */
130     struct hmap ports;          /* "struct port"s indexed by name. */
131     struct hmap ifaces;         /* "struct iface"s indexed by ofp_port. */
132     struct hmap iface_by_name;  /* "struct iface"s indexed by name. */
133
134     /* Port mirroring. */
135     struct hmap mirrors;        /* "struct mirror" indexed by UUID. */
136
137     /* Synthetic local port if necessary. */
138     struct ovsrec_port synth_local_port;
139     struct ovsrec_interface synth_local_iface;
140     struct ovsrec_interface *synth_local_ifacep;
141 };
142
143 /* All bridges, indexed by name. */
144 static struct hmap all_bridges = HMAP_INITIALIZER(&all_bridges);
145
146 /* OVSDB IDL used to obtain configuration. */
147 static struct ovsdb_idl *idl;
148
149 /* Each time this timer expires, the bridge fetches systems and interface
150  * statistics and pushes them into the database. */
151 #define STATS_INTERVAL (5 * 1000) /* In milliseconds. */
152 static long long int stats_timer = LLONG_MIN;
153
154 /* Stores the time after which rate limited statistics may be written to the
155  * database.  Only updated when changes to the database require rate limiting.
156  */
157 #define DB_LIMIT_INTERVAL (1 * 1000) /* In milliseconds. */
158 static long long int db_limiter = LLONG_MIN;
159
160 static void add_del_bridges(const struct ovsrec_open_vswitch *);
161 static void bridge_del_dps(void);
162 static bool bridge_add_dp(struct bridge *);
163 static void bridge_create(const struct ovsrec_bridge *);
164 static void bridge_destroy(struct bridge *);
165 static struct bridge *bridge_lookup(const char *name);
166 static unixctl_cb_func bridge_unixctl_dump_flows;
167 static unixctl_cb_func bridge_unixctl_reconnect;
168 static size_t bridge_get_controllers(const struct bridge *br,
169                                      struct ovsrec_controller ***controllersp);
170 static void bridge_add_del_ports(struct bridge *);
171 static void bridge_add_ofproto_ports(struct bridge *);
172 static void bridge_del_ofproto_ports(struct bridge *);
173 static void bridge_refresh_ofp_port(struct bridge *);
174 static void bridge_configure_datapath_id(struct bridge *);
175 static void bridge_configure_netflow(struct bridge *);
176 static void bridge_configure_sflow(struct bridge *, int *sflow_bridge_number);
177 static void bridge_configure_remotes(struct bridge *,
178                                      const struct sockaddr_in *managers,
179                                      size_t n_managers);
180 static void bridge_pick_local_hw_addr(struct bridge *,
181                                       uint8_t ea[ETH_ADDR_LEN],
182                                       struct iface **hw_addr_iface);
183 static uint64_t bridge_pick_datapath_id(struct bridge *,
184                                         const uint8_t bridge_ea[ETH_ADDR_LEN],
185                                         struct iface *hw_addr_iface);
186 static uint64_t dpid_from_hash(const void *, size_t nbytes);
187 static bool bridge_has_bond_fake_iface(const struct bridge *,
188                                        const char *name);
189 static bool port_is_bond_fake_iface(const struct port *);
190
191 static unixctl_cb_func cfm_unixctl_show;
192 static unixctl_cb_func qos_unixctl_show;
193
194 static struct port *port_create(struct bridge *, const struct ovsrec_port *);
195 static void port_add_ifaces(struct port *);
196 static void port_del_ifaces(struct port *);
197 static void port_destroy(struct port *);
198 static struct port *port_lookup(const struct bridge *, const char *name);
199 static void port_configure(struct port *);
200 static struct lacp_settings *port_configure_lacp(struct port *,
201                                                  struct lacp_settings *);
202 static void port_configure_bond(struct port *, struct bond_settings *);
203
204 static void bridge_configure_mirrors(struct bridge *);
205 static struct mirror *mirror_create(struct bridge *,
206                                     const struct ovsrec_mirror *);
207 static void mirror_destroy(struct mirror *);
208 static bool mirror_configure(struct mirror *, const struct ovsrec_mirror *);
209
210 static void iface_configure_lacp(struct iface *, struct lacp_slave_settings *);
211 static struct iface *iface_create(struct port *port,
212                                   const struct ovsrec_interface *if_cfg);
213 static void iface_destroy(struct iface *);
214 static struct iface *iface_lookup(const struct bridge *, const char *name);
215 static struct iface *iface_find(const char *name);
216 static struct iface *iface_from_ofp_port(const struct bridge *,
217                                          uint16_t ofp_port);
218 static void iface_set_mac(struct iface *);
219 static void iface_set_ofport(const struct ovsrec_interface *, int64_t ofport);
220 static void iface_configure_qos(struct iface *, const struct ovsrec_qos *);
221 static void iface_configure_cfm(struct iface *);
222 static bool iface_refresh_cfm_stats(struct iface *iface);
223 static bool iface_get_carrier(const struct iface *);
224 static bool iface_is_synthetic(const struct iface *);
225
226 static void shash_from_ovs_idl_map(char **keys, char **values, size_t n,
227                                    struct shash *);
228 static void shash_to_ovs_idl_map(struct shash *,
229                                  char ***keys, char ***values, size_t *n);
230 \f
231 /* Public functions. */
232
233 /* Initializes the bridge module, configuring it to obtain its configuration
234  * from an OVSDB server accessed over 'remote', which should be a string in a
235  * form acceptable to ovsdb_idl_create(). */
236 void
237 bridge_init(const char *remote)
238 {
239     /* Create connection to database. */
240     idl = ovsdb_idl_create(remote, &ovsrec_idl_class, true);
241
242     ovsdb_idl_omit_alert(idl, &ovsrec_open_vswitch_col_cur_cfg);
243     ovsdb_idl_omit_alert(idl, &ovsrec_open_vswitch_col_statistics);
244     ovsdb_idl_omit(idl, &ovsrec_open_vswitch_col_external_ids);
245     ovsdb_idl_omit(idl, &ovsrec_open_vswitch_col_ovs_version);
246     ovsdb_idl_omit(idl, &ovsrec_open_vswitch_col_db_version);
247     ovsdb_idl_omit(idl, &ovsrec_open_vswitch_col_system_type);
248     ovsdb_idl_omit(idl, &ovsrec_open_vswitch_col_system_version);
249
250     ovsdb_idl_omit_alert(idl, &ovsrec_bridge_col_datapath_id);
251     ovsdb_idl_omit(idl, &ovsrec_bridge_col_external_ids);
252
253     ovsdb_idl_omit(idl, &ovsrec_port_col_external_ids);
254     ovsdb_idl_omit(idl, &ovsrec_port_col_fake_bridge);
255
256     ovsdb_idl_omit_alert(idl, &ovsrec_interface_col_admin_state);
257     ovsdb_idl_omit_alert(idl, &ovsrec_interface_col_duplex);
258     ovsdb_idl_omit_alert(idl, &ovsrec_interface_col_link_speed);
259     ovsdb_idl_omit_alert(idl, &ovsrec_interface_col_link_state);
260     ovsdb_idl_omit_alert(idl, &ovsrec_interface_col_mtu);
261     ovsdb_idl_omit_alert(idl, &ovsrec_interface_col_ofport);
262     ovsdb_idl_omit_alert(idl, &ovsrec_interface_col_statistics);
263     ovsdb_idl_omit_alert(idl, &ovsrec_interface_col_status);
264     ovsdb_idl_omit(idl, &ovsrec_interface_col_external_ids);
265
266     ovsdb_idl_omit_alert(idl, &ovsrec_controller_col_is_connected);
267     ovsdb_idl_omit_alert(idl, &ovsrec_controller_col_role);
268     ovsdb_idl_omit_alert(idl, &ovsrec_controller_col_status);
269     ovsdb_idl_omit(idl, &ovsrec_controller_col_external_ids);
270
271     ovsdb_idl_omit_alert(idl, &ovsrec_maintenance_point_col_fault);
272
273     ovsdb_idl_omit_alert(idl, &ovsrec_monitor_col_fault);
274
275     ovsdb_idl_omit(idl, &ovsrec_qos_col_external_ids);
276
277     ovsdb_idl_omit(idl, &ovsrec_queue_col_external_ids);
278
279     ovsdb_idl_omit(idl, &ovsrec_mirror_col_external_ids);
280
281     ovsdb_idl_omit(idl, &ovsrec_netflow_col_external_ids);
282
283     ovsdb_idl_omit(idl, &ovsrec_sflow_col_external_ids);
284
285     ovsdb_idl_omit(idl, &ovsrec_manager_col_external_ids);
286     ovsdb_idl_omit(idl, &ovsrec_manager_col_inactivity_probe);
287     ovsdb_idl_omit(idl, &ovsrec_manager_col_is_connected);
288     ovsdb_idl_omit(idl, &ovsrec_manager_col_max_backoff);
289     ovsdb_idl_omit(idl, &ovsrec_manager_col_status);
290
291     ovsdb_idl_omit(idl, &ovsrec_ssl_col_external_ids);
292
293     /* Register unixctl commands. */
294     unixctl_command_register("cfm/show", cfm_unixctl_show, NULL);
295     unixctl_command_register("qos/show", qos_unixctl_show, NULL);
296     unixctl_command_register("bridge/dump-flows", bridge_unixctl_dump_flows,
297                              NULL);
298     unixctl_command_register("bridge/reconnect", bridge_unixctl_reconnect,
299                              NULL);
300     lacp_init();
301     bond_init();
302 }
303
304 void
305 bridge_exit(void)
306 {
307     struct bridge *br, *next_br;
308
309     HMAP_FOR_EACH_SAFE (br, next_br, node, &all_bridges) {
310         bridge_destroy(br);
311     }
312     ovsdb_idl_destroy(idl);
313 }
314
315 /* Looks at the list of managers in 'ovs_cfg' and extracts their remote IP
316  * addresses and ports into '*managersp' and '*n_managersp'.  The caller is
317  * responsible for freeing '*managersp' (with free()).
318  *
319  * You may be asking yourself "why does ovs-vswitchd care?", because
320  * ovsdb-server is responsible for connecting to the managers, and ovs-vswitchd
321  * should not be and in fact is not directly involved in that.  But
322  * ovs-vswitchd needs to make sure that ovsdb-server can reach the managers, so
323  * it has to tell in-band control where the managers are to enable that.
324  * (Thus, only managers connected in-band are collected.)
325  */
326 static void
327 collect_in_band_managers(const struct ovsrec_open_vswitch *ovs_cfg,
328                          struct sockaddr_in **managersp, size_t *n_managersp)
329 {
330     struct sockaddr_in *managers = NULL;
331     size_t n_managers = 0;
332     struct sset targets;
333     size_t i;
334
335     /* Collect all of the potential targets from the "targets" columns of the
336      * rows pointed to by "manager_options", excluding any that are
337      * out-of-band. */
338     sset_init(&targets);
339     for (i = 0; i < ovs_cfg->n_manager_options; i++) {
340         struct ovsrec_manager *m = ovs_cfg->manager_options[i];
341
342         if (m->connection_mode && !strcmp(m->connection_mode, "out-of-band")) {
343             sset_find_and_delete(&targets, m->target);
344         } else {
345             sset_add(&targets, m->target);
346         }
347     }
348
349     /* Now extract the targets' IP addresses. */
350     if (!sset_is_empty(&targets)) {
351         const char *target;
352
353         managers = xmalloc(sset_count(&targets) * sizeof *managers);
354         SSET_FOR_EACH (target, &targets) {
355             struct sockaddr_in *sin = &managers[n_managers];
356
357             if ((!strncmp(target, "tcp:", 4)
358                  && inet_parse_active(target + 4, JSONRPC_TCP_PORT, sin)) ||
359                 (!strncmp(target, "ssl:", 4)
360                  && inet_parse_active(target + 4, JSONRPC_SSL_PORT, sin))) {
361                 n_managers++;
362             }
363         }
364     }
365     sset_destroy(&targets);
366
367     *managersp = managers;
368     *n_managersp = n_managers;
369 }
370
371 static void
372 bridge_reconfigure(const struct ovsrec_open_vswitch *ovs_cfg)
373 {
374     struct sockaddr_in *managers;
375     struct bridge *br, *next;
376     int sflow_bridge_number;
377     size_t n_managers;
378
379     COVERAGE_INC(bridge_reconfigure);
380
381     /* Create and destroy "struct bridge"s, "struct port"s, and "struct
382      * iface"s according to 'ovs_cfg', with only very minimal configuration
383      * otherwise.
384      *
385      * This is purely an update to bridge data structures.  Nothing is pushed
386      * down to ofproto or lower layers. */
387     add_del_bridges(ovs_cfg);
388     HMAP_FOR_EACH (br, node, &all_bridges) {
389         bridge_add_del_ports(br);
390     }
391
392     /* Delete all datapaths and datapath ports that are no longer configured.
393      *
394      * The kernel will reject any attempt to add a given port to a datapath if
395      * that port already belongs to a different datapath, so we must do all
396      * port deletions before any port additions.  A datapath always has a
397      * "local port" so we must delete not-configured datapaths too. */
398     bridge_del_dps();
399     HMAP_FOR_EACH (br, node, &all_bridges) {
400         if (br->ofproto) {
401             bridge_del_ofproto_ports(br);
402         }
403     }
404
405     /* Create datapaths and datapath ports that are missing.
406      *
407      * After this is done, we have our final set of bridges, ports, and
408      * interfaces.  Every "struct bridge" has an ofproto, every "struct port"
409      * has at least one iface, every "struct iface" has a valid ofp_port and
410      * netdev. */
411     HMAP_FOR_EACH_SAFE (br, next, node, &all_bridges) {
412         if (!br->ofproto && !bridge_add_dp(br)) {
413             bridge_destroy(br);
414         }
415     }
416     HMAP_FOR_EACH (br, node, &all_bridges) {
417         bridge_refresh_ofp_port(br);
418         bridge_add_ofproto_ports(br);
419     }
420
421     /* Complete the configuration. */
422     sflow_bridge_number = 0;
423     collect_in_band_managers(ovs_cfg, &managers, &n_managers);
424     HMAP_FOR_EACH (br, node, &all_bridges) {
425         struct port *port;
426
427         HMAP_FOR_EACH (port, hmap_node, &br->ports) {
428             struct iface *iface;
429
430             port_configure(port);
431
432             HMAP_FOR_EACH (iface, ofp_port_node, &br->ifaces) {
433                 iface_configure_cfm(iface);
434                 iface_configure_qos(iface, port->cfg->qos);
435                 iface_set_mac(iface);
436             }
437         }
438         bridge_configure_mirrors(br);
439         bridge_configure_datapath_id(br);
440         bridge_configure_remotes(br, managers, n_managers);
441         bridge_configure_netflow(br);
442         bridge_configure_sflow(br, &sflow_bridge_number);
443     }
444     free(managers);
445
446     /* ovs-vswitchd has completed initialization, so allow the process that
447      * forked us to exit successfully. */
448     daemonize_complete();
449 }
450
451 /* Iterate over all system dpifs and delete any of them that do not have a
452  * configured bridge or that are the wrong type. */
453 static void
454 bridge_del_dps(void)
455 {
456     struct sset dpif_names;
457     struct sset dpif_types;
458     const char *type;
459
460     sset_init(&dpif_names);
461     sset_init(&dpif_types);
462     dp_enumerate_types(&dpif_types);
463     SSET_FOR_EACH (type, &dpif_types) {
464         const char *name;
465
466         dp_enumerate_names(type, &dpif_names);
467         SSET_FOR_EACH (name, &dpif_names) {
468             struct bridge *br = bridge_lookup(name);
469             if (!br || strcmp(type, br->type)) {
470                 struct dpif *dpif;
471
472                 if (!dpif_open(name, type, &dpif)) {
473                     dpif_delete(dpif);
474                     dpif_close(dpif);
475                 }
476             }
477         }
478     }
479     sset_destroy(&dpif_names);
480     sset_destroy(&dpif_types);
481 }
482
483 static bool
484 bridge_add_dp(struct bridge *br)
485 {
486     int error = ofproto_create(br->name, br->type, &br->ofproto);
487     if (error) {
488         VLOG_ERR("failed to create bridge %s: %s", br->name, strerror(error));
489         return false;
490     }
491     return true;
492 }
493
494 static void
495 port_configure(struct port *port)
496 {
497     const struct ovsrec_port *cfg = port->cfg;
498     struct bond_settings bond_settings;
499     struct lacp_settings lacp_settings;
500     struct ofproto_bundle_settings s;
501     struct iface *iface;
502
503     /* Get name. */
504     s.name = port->name;
505
506     /* Get slaves. */
507     s.n_slaves = 0;
508     s.slaves = xmalloc(list_size(&port->ifaces) * sizeof *s.slaves);
509     LIST_FOR_EACH (iface, port_elem, &port->ifaces) {
510         s.slaves[s.n_slaves++] = iface->ofp_port;
511     }
512
513     /* Get VLAN tag. */
514     s.vlan = -1;
515     if (cfg->tag) {
516         if (list_is_short(&port->ifaces)) {
517             if (*cfg->tag >= 0 && *cfg->tag <= 4095) {
518                 s.vlan = *cfg->tag;
519                 VLOG_DBG("port %s: assigning VLAN tag %d", port->name, s.vlan);
520             }
521         } else {
522             /* It's possible that bonded, VLAN-tagged ports make sense.  Maybe
523              * they even work as-is.  But they have not been tested. */
524             VLOG_WARN("port %s: VLAN tags not supported on bonded ports",
525                       port->name);
526         }
527     }
528
529     /* Get VLAN trunks. */
530     s.trunks = NULL;
531     if (s.vlan < 0 && cfg->n_trunks) {
532         s.trunks = vlan_bitmap_from_array(cfg->trunks, cfg->n_trunks);
533     } else if (s.vlan >= 0 && cfg->n_trunks) {
534         VLOG_ERR("port %s: ignoring trunks in favor of implicit vlan",
535                  port->name);
536     }
537
538     /* Get LACP settings. */
539     s.lacp = port_configure_lacp(port, &lacp_settings);
540     if (s.lacp) {
541         size_t i = 0;
542
543         s.lacp_slaves = xmalloc(s.n_slaves * sizeof *s.lacp_slaves);
544         LIST_FOR_EACH (iface, port_elem, &port->ifaces) {
545             iface_configure_lacp(iface, &s.lacp_slaves[i++]);
546         }
547     } else {
548         s.lacp_slaves = NULL;
549     }
550
551     /* Get bond settings. */
552     if (s.n_slaves > 1) {
553         port_configure_bond(port, &bond_settings);
554         s.bond = &bond_settings;
555     } else {
556         s.bond = NULL;
557     }
558
559     /* Register. */
560     ofproto_bundle_register(port->bridge->ofproto, port, &s);
561
562     /* Clean up. */
563     free(s.trunks);
564     free(s.lacp_slaves);
565 }
566
567 /* Pick local port hardware address and datapath ID for 'br'. */
568 static void
569 bridge_configure_datapath_id(struct bridge *br)
570 {
571     uint8_t ea[ETH_ADDR_LEN];
572     uint64_t dpid;
573     struct iface *local_iface;
574     struct iface *hw_addr_iface;
575     char *dpid_string;
576
577     bridge_pick_local_hw_addr(br, ea, &hw_addr_iface);
578     local_iface = iface_from_ofp_port(br, OFPP_LOCAL);
579     if (local_iface) {
580         int error = netdev_set_etheraddr(local_iface->netdev, ea);
581         if (error) {
582             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
583             VLOG_ERR_RL(&rl, "bridge %s: failed to set bridge "
584                         "Ethernet address: %s",
585                         br->name, strerror(error));
586         }
587     }
588     memcpy(br->ea, ea, ETH_ADDR_LEN);
589
590     dpid = bridge_pick_datapath_id(br, ea, hw_addr_iface);
591     ofproto_set_datapath_id(br->ofproto, dpid);
592
593     dpid_string = xasprintf("%016"PRIx64, dpid);
594     ovsrec_bridge_set_datapath_id(br->cfg, dpid_string);
595     free(dpid_string);
596 }
597
598 /* Set NetFlow configuration on 'br'. */
599 static void
600 bridge_configure_netflow(struct bridge *br)
601 {
602     struct ovsrec_netflow *cfg = br->cfg->netflow;
603     struct netflow_options opts;
604
605     if (!cfg) {
606         ofproto_set_netflow(br->ofproto, NULL);
607         return;
608     }
609
610     memset(&opts, 0, sizeof opts);
611
612     /* Get default NetFlow configuration from datapath.
613      * Apply overrides from 'cfg'. */
614     ofproto_get_netflow_ids(br->ofproto, &opts.engine_type, &opts.engine_id);
615     if (cfg->engine_type) {
616         opts.engine_type = *cfg->engine_type;
617     }
618     if (cfg->engine_id) {
619         opts.engine_id = *cfg->engine_id;
620     }
621
622     /* Configure active timeout interval. */
623     opts.active_timeout = cfg->active_timeout;
624     if (!opts.active_timeout) {
625         opts.active_timeout = -1;
626     } else if (opts.active_timeout < 0) {
627         VLOG_WARN("bridge %s: active timeout interval set to negative "
628                   "value, using default instead (%d seconds)", br->name,
629                   NF_ACTIVE_TIMEOUT_DEFAULT);
630         opts.active_timeout = -1;
631     }
632
633     /* Add engine ID to interface number to disambiguate bridgs? */
634     opts.add_id_to_iface = cfg->add_id_to_interface;
635     if (opts.add_id_to_iface) {
636         if (opts.engine_id > 0x7f) {
637             VLOG_WARN("bridge %s: NetFlow port mangling may conflict with "
638                       "another vswitch, choose an engine id less than 128",
639                       br->name);
640         }
641         if (hmap_count(&br->ports) > 508) {
642             VLOG_WARN("bridge %s: NetFlow port mangling will conflict with "
643                       "another port when more than 508 ports are used",
644                       br->name);
645         }
646     }
647
648     /* Collectors. */
649     sset_init(&opts.collectors);
650     sset_add_array(&opts.collectors, cfg->targets, cfg->n_targets);
651
652     /* Configure. */
653     if (ofproto_set_netflow(br->ofproto, &opts)) {
654         VLOG_ERR("bridge %s: problem setting netflow collectors", br->name);
655     }
656     sset_destroy(&opts.collectors);
657 }
658
659 /* Set sFlow configuration on 'br'. */
660 static void
661 bridge_configure_sflow(struct bridge *br, int *sflow_bridge_number)
662 {
663     const struct ovsrec_sflow *cfg = br->cfg->sflow;
664     struct ovsrec_controller **controllers;
665     struct ofproto_sflow_options oso;
666     size_t n_controllers;
667     size_t i;
668
669     if (!cfg) {
670         ofproto_set_sflow(br->ofproto, NULL);
671         return;
672     }
673
674     memset(&oso, 0, sizeof oso);
675
676     sset_init(&oso.targets);
677     sset_add_array(&oso.targets, cfg->targets, cfg->n_targets);
678
679     oso.sampling_rate = SFL_DEFAULT_SAMPLING_RATE;
680     if (cfg->sampling) {
681         oso.sampling_rate = *cfg->sampling;
682     }
683
684     oso.polling_interval = SFL_DEFAULT_POLLING_INTERVAL;
685     if (cfg->polling) {
686         oso.polling_interval = *cfg->polling;
687     }
688
689     oso.header_len = SFL_DEFAULT_HEADER_SIZE;
690     if (cfg->header) {
691         oso.header_len = *cfg->header;
692     }
693
694     oso.sub_id = (*sflow_bridge_number)++;
695     oso.agent_device = cfg->agent;
696
697     oso.control_ip = NULL;
698     n_controllers = bridge_get_controllers(br, &controllers);
699     for (i = 0; i < n_controllers; i++) {
700         if (controllers[i]->local_ip) {
701             oso.control_ip = controllers[i]->local_ip;
702             break;
703         }
704     }
705     ofproto_set_sflow(br->ofproto, &oso);
706
707     sset_destroy(&oso.targets);
708 }
709
710 static bool
711 bridge_has_bond_fake_iface(const struct bridge *br, const char *name)
712 {
713     const struct port *port = port_lookup(br, name);
714     return port && port_is_bond_fake_iface(port);
715 }
716
717 static bool
718 port_is_bond_fake_iface(const struct port *port)
719 {
720     return port->cfg->bond_fake_iface && !list_is_short(&port->ifaces);
721 }
722
723 static void
724 add_del_bridges(const struct ovsrec_open_vswitch *cfg)
725 {
726     struct bridge *br, *next;
727     struct shash new_br;
728     size_t i;
729
730     /* Collect new bridges' names and types. */
731     shash_init(&new_br);
732     for (i = 0; i < cfg->n_bridges; i++) {
733         const struct ovsrec_bridge *br_cfg = cfg->bridges[i];
734         if (!shash_add_once(&new_br, br_cfg->name, br_cfg)) {
735             VLOG_WARN("bridge %s specified twice", br_cfg->name);
736         }
737     }
738
739     /* Get rid of deleted bridges or those whose types have changed.
740      * Update 'cfg' of bridges that still exist. */
741     HMAP_FOR_EACH_SAFE (br, next, node, &all_bridges) {
742         br->cfg = shash_find_data(&new_br, br->name);
743         if (!br->cfg || strcmp(br->type,
744                                dpif_normalize_type(br->cfg->datapath_type))) {
745             bridge_destroy(br);
746         }
747     }
748
749     /* Add new bridges. */
750     for (i = 0; i < cfg->n_bridges; i++) {
751         const struct ovsrec_bridge *br_cfg = cfg->bridges[i];
752         struct bridge *br = bridge_lookup(br_cfg->name);
753         if (!br) {
754             bridge_create(br_cfg);
755         }
756     }
757
758     shash_destroy(&new_br);
759 }
760
761 /* Delete each ofproto port on 'br' that doesn't have a corresponding "struct
762  * iface".
763  *
764  * The kernel will reject any attempt to add a given port to a datapath if that
765  * port already belongs to a different datapath, so we must do all port
766  * deletions before any port additions. */
767 static void
768 bridge_del_ofproto_ports(struct bridge *br)
769 {
770     struct ofproto_port_dump dump;
771     struct ofproto_port ofproto_port;
772
773     OFPROTO_PORT_FOR_EACH (&ofproto_port, &dump, br->ofproto) {
774         const char *name = ofproto_port.name;
775         struct iface *iface;
776         const char *type;
777         int error;
778
779         /* Ignore the local port.  We can't change it anyhow. */
780         if (!strcmp(name, br->name)) {
781             continue;
782         }
783
784         /* Get the type that 'ofproto_port' should have (ordinarily the
785          * type of its corresponding iface) or NULL if it should be
786          * deleted. */
787         iface = iface_lookup(br, name);
788         type = (iface ? iface->type
789                 : bridge_has_bond_fake_iface(br, name) ? "internal"
790                 : NULL);
791
792         /* If it's the wrong type then delete the ofproto port. */
793         if (type
794             && !strcmp(ofproto_port.type, type)
795             && (!iface || !iface->netdev
796                 || !strcmp(netdev_get_type(iface->netdev), type))) {
797             continue;
798         }
799         error = ofproto_port_del(br->ofproto, ofproto_port.ofp_port);
800         if (error) {
801             VLOG_WARN("bridge %s: failed to remove %s interface (%s)",
802                       br->name, name, strerror(error));
803         }
804         if (iface) {
805             ofproto_port_unregister(br->ofproto, ofproto_port.ofp_port);
806             netdev_close(iface->netdev);
807             iface->netdev = NULL;
808         }
809     }
810 }
811
812 static void
813 iface_set_ofp_port(struct iface *iface, int ofp_port)
814 {
815     struct bridge *br = iface->port->bridge;
816
817     assert(iface->ofp_port < 0 && ofp_port >= 0);
818     iface->ofp_port = ofp_port;
819     hmap_insert(&br->ifaces, &iface->ofp_port_node, hash_int(ofp_port, 0));
820
821 }
822
823 static void
824 bridge_refresh_ofp_port(struct bridge *br)
825 {
826     struct ofproto_port_dump dump;
827     struct ofproto_port ofproto_port;
828     struct port *port;
829
830     /* Clear all the "ofp_port"es. */
831     hmap_clear(&br->ifaces);
832     HMAP_FOR_EACH (port, hmap_node, &br->ports) {
833         struct iface *iface;
834
835         LIST_FOR_EACH (iface, port_elem, &port->ifaces) {
836             iface->ofp_port = -1;
837         }
838     }
839
840     /* Obtain the correct "ofp_port"s from ofproto. */
841     OFPROTO_PORT_FOR_EACH (&ofproto_port, &dump, br->ofproto) {
842         struct iface *iface = iface_lookup(br, ofproto_port.name);
843         if (iface) {
844             if (iface->ofp_port >= 0) {
845                 VLOG_WARN("bridge %s: interface %s reported twice",
846                           br->name, ofproto_port.name);
847             } else if (iface_from_ofp_port(br, ofproto_port.ofp_port)) {
848                 VLOG_WARN("bridge %s: interface %"PRIu16" reported twice",
849                           br->name, ofproto_port.ofp_port);
850             } else {
851                 iface_set_ofp_port(iface, ofproto_port.ofp_port);
852             }
853         }
854     }
855 }
856
857 /* Add a dpif port for any "struct iface" that doesn't have one.
858  * Delete any "struct iface" for which this fails.
859  * Delete any "struct port" that thereby ends up with no ifaces. */
860 static void
861 bridge_add_ofproto_ports(struct bridge *br)
862 {
863     struct port *port, *next_port;
864
865     HMAP_FOR_EACH_SAFE (port, next_port, hmap_node, &br->ports) {
866         struct iface *iface, *next_iface;
867         struct ofproto_port ofproto_port;
868
869         LIST_FOR_EACH_SAFE (iface, next_iface, port_elem, &port->ifaces) {
870             struct shash args;
871             int error;
872
873             /* Open the netdev or reconfigure it. */
874             shash_init(&args);
875             shash_from_ovs_idl_map(iface->cfg->key_options,
876                                    iface->cfg->value_options,
877                                    iface->cfg->n_options, &args);
878             if (!iface->netdev) {
879                 struct netdev_options options;
880                 options.name = iface->name;
881                 options.type = iface->type;
882                 options.args = &args;
883                 options.ethertype = NETDEV_ETH_TYPE_NONE;
884                 error = netdev_open(&options, &iface->netdev);
885             } else {
886                 error = netdev_set_config(iface->netdev, &args);
887             }
888             shash_destroy(&args);
889             if (error) {
890                 VLOG_WARN("could not %s network device %s (%s)",
891                           iface->netdev ? "reconfigure" : "open",
892                           iface->name, strerror(error));
893             }
894
895             /* Add the port, if necessary. */
896             if (iface->netdev && iface->ofp_port < 0) {
897                 uint16_t ofp_port;
898                 int error;
899
900                 error = ofproto_port_add(br->ofproto, iface->netdev,
901                                          &ofp_port);
902                 if (!error) {
903                     iface_set_ofp_port(iface, ofp_port);
904                 } else {
905                     netdev_close(iface->netdev);
906                     iface->netdev = NULL;
907                 }
908             }
909
910             /* Delete the iface if  */
911             if (iface->netdev && iface->ofp_port >= 0) {
912                 VLOG_DBG("bridge %s: interface %s is on port %d",
913                          br->name, iface->name, iface->ofp_port);
914             } else {
915                 if (iface->netdev) {
916                     VLOG_ERR("bridge %s: missing %s interface, dropping",
917                              br->name, iface->name);
918                 } else {
919                     /* We already reported a related error, don't bother
920                      * duplicating it. */
921                 }
922                 iface_set_ofport(iface->cfg, -1);
923                 iface_destroy(iface);
924             }
925         }
926         if (list_is_empty(&port->ifaces)) {
927             VLOG_WARN("%s port has no interfaces, dropping", port->name);
928             port_destroy(port);
929             continue;
930         }
931
932         /* Add bond fake iface if necessary. */
933         if (port_is_bond_fake_iface(port)) {
934             if (ofproto_port_query_by_name(br->ofproto, port->name,
935                                            &ofproto_port)) {
936                 struct netdev_options options;
937                 struct netdev *netdev;
938                 int error;
939
940                 options.name = port->name;
941                 options.type = "internal";
942                 options.args = NULL;
943                 options.ethertype = NETDEV_ETH_TYPE_NONE;
944                 error = netdev_open(&options, &netdev);
945                 if (!error) {
946                     ofproto_port_add(br->ofproto, netdev, NULL);
947                     netdev_close(netdev);
948                 } else {
949                     VLOG_WARN("could not open network device %s (%s)",
950                               port->name, strerror(error));
951                 }
952             } else {
953                 /* Already exists, nothing to do. */
954                 ofproto_port_destroy(&ofproto_port);
955             }
956             ofproto_port_destroy(&ofproto_port);
957         }
958     }
959 }
960
961 static const char *
962 get_ovsrec_key_value(const struct ovsdb_idl_row *row,
963                      const struct ovsdb_idl_column *column,
964                      const char *key)
965 {
966     const struct ovsdb_datum *datum;
967     union ovsdb_atom atom;
968     unsigned int idx;
969
970     datum = ovsdb_idl_get(row, column, OVSDB_TYPE_STRING, OVSDB_TYPE_STRING);
971     atom.string = (char *) key;
972     idx = ovsdb_datum_find_key(datum, &atom, OVSDB_TYPE_STRING);
973     return idx == UINT_MAX ? NULL : datum->values[idx].string;
974 }
975
976 static const char *
977 bridge_get_other_config(const struct ovsrec_bridge *br_cfg, const char *key)
978 {
979     return get_ovsrec_key_value(&br_cfg->header_,
980                                 &ovsrec_bridge_col_other_config, key);
981 }
982
983 static void
984 bridge_pick_local_hw_addr(struct bridge *br, uint8_t ea[ETH_ADDR_LEN],
985                           struct iface **hw_addr_iface)
986 {
987     const char *hwaddr;
988     struct port *port;
989     int error;
990
991     *hw_addr_iface = NULL;
992
993     /* Did the user request a particular MAC? */
994     hwaddr = bridge_get_other_config(br->cfg, "hwaddr");
995     if (hwaddr && eth_addr_from_string(hwaddr, ea)) {
996         if (eth_addr_is_multicast(ea)) {
997             VLOG_ERR("bridge %s: cannot set MAC address to multicast "
998                      "address "ETH_ADDR_FMT, br->name, ETH_ADDR_ARGS(ea));
999         } else if (eth_addr_is_zero(ea)) {
1000             VLOG_ERR("bridge %s: cannot set MAC address to zero", br->name);
1001         } else {
1002             return;
1003         }
1004     }
1005
1006     /* Otherwise choose the minimum non-local MAC address among all of the
1007      * interfaces. */
1008     memset(ea, 0xff, ETH_ADDR_LEN);
1009     HMAP_FOR_EACH (port, hmap_node, &br->ports) {
1010         uint8_t iface_ea[ETH_ADDR_LEN];
1011         struct iface *candidate;
1012         struct iface *iface;
1013
1014         /* Mirror output ports don't participate. */
1015         if (ofproto_is_mirror_output_bundle(br->ofproto, port)) {
1016             continue;
1017         }
1018
1019         /* Choose the MAC address to represent the port. */
1020         iface = NULL;
1021         if (port->cfg->mac && eth_addr_from_string(port->cfg->mac, iface_ea)) {
1022             /* Find the interface with this Ethernet address (if any) so that
1023              * we can provide the correct devname to the caller. */
1024             LIST_FOR_EACH (candidate, port_elem, &port->ifaces) {
1025                 uint8_t candidate_ea[ETH_ADDR_LEN];
1026                 if (!netdev_get_etheraddr(candidate->netdev, candidate_ea)
1027                     && eth_addr_equals(iface_ea, candidate_ea)) {
1028                     iface = candidate;
1029                 }
1030             }
1031         } else {
1032             /* Choose the interface whose MAC address will represent the port.
1033              * The Linux kernel bonding code always chooses the MAC address of
1034              * the first slave added to a bond, and the Fedora networking
1035              * scripts always add slaves to a bond in alphabetical order, so
1036              * for compatibility we choose the interface with the name that is
1037              * first in alphabetical order. */
1038             LIST_FOR_EACH (candidate, port_elem, &port->ifaces) {
1039                 if (!iface || strcmp(candidate->name, iface->name) < 0) {
1040                     iface = candidate;
1041                 }
1042             }
1043
1044             /* The local port doesn't count (since we're trying to choose its
1045              * MAC address anyway). */
1046             if (iface->ofp_port == OFPP_LOCAL) {
1047                 continue;
1048             }
1049
1050             /* Grab MAC. */
1051             error = netdev_get_etheraddr(iface->netdev, iface_ea);
1052             if (error) {
1053                 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
1054                 VLOG_ERR_RL(&rl, "failed to obtain Ethernet address of %s: %s",
1055                             iface->name, strerror(error));
1056                 continue;
1057             }
1058         }
1059
1060         /* Compare against our current choice. */
1061         if (!eth_addr_is_multicast(iface_ea) &&
1062             !eth_addr_is_local(iface_ea) &&
1063             !eth_addr_is_reserved(iface_ea) &&
1064             !eth_addr_is_zero(iface_ea) &&
1065             eth_addr_compare_3way(iface_ea, ea) < 0)
1066         {
1067             memcpy(ea, iface_ea, ETH_ADDR_LEN);
1068             *hw_addr_iface = iface;
1069         }
1070     }
1071     if (eth_addr_is_multicast(ea)) {
1072         memcpy(ea, br->default_ea, ETH_ADDR_LEN);
1073         *hw_addr_iface = NULL;
1074         VLOG_WARN("bridge %s: using default bridge Ethernet "
1075                   "address "ETH_ADDR_FMT, br->name, ETH_ADDR_ARGS(ea));
1076     } else {
1077         VLOG_DBG("bridge %s: using bridge Ethernet address "ETH_ADDR_FMT,
1078                  br->name, ETH_ADDR_ARGS(ea));
1079     }
1080 }
1081
1082 /* Choose and returns the datapath ID for bridge 'br' given that the bridge
1083  * Ethernet address is 'bridge_ea'.  If 'bridge_ea' is the Ethernet address of
1084  * an interface on 'br', then that interface must be passed in as
1085  * 'hw_addr_iface'; if 'bridge_ea' was derived some other way, then
1086  * 'hw_addr_iface' must be passed in as a null pointer. */
1087 static uint64_t
1088 bridge_pick_datapath_id(struct bridge *br,
1089                         const uint8_t bridge_ea[ETH_ADDR_LEN],
1090                         struct iface *hw_addr_iface)
1091 {
1092     /*
1093      * The procedure for choosing a bridge MAC address will, in the most
1094      * ordinary case, also choose a unique MAC that we can use as a datapath
1095      * ID.  In some special cases, though, multiple bridges will end up with
1096      * the same MAC address.  This is OK for the bridges, but it will confuse
1097      * the OpenFlow controller, because each datapath needs a unique datapath
1098      * ID.
1099      *
1100      * Datapath IDs must be unique.  It is also very desirable that they be
1101      * stable from one run to the next, so that policy set on a datapath
1102      * "sticks".
1103      */
1104     const char *datapath_id;
1105     uint64_t dpid;
1106
1107     datapath_id = bridge_get_other_config(br->cfg, "datapath-id");
1108     if (datapath_id && dpid_from_string(datapath_id, &dpid)) {
1109         return dpid;
1110     }
1111
1112     if (hw_addr_iface) {
1113         int vlan;
1114         if (!netdev_get_vlan_vid(hw_addr_iface->netdev, &vlan)) {
1115             /*
1116              * A bridge whose MAC address is taken from a VLAN network device
1117              * (that is, a network device created with vconfig(8) or similar
1118              * tool) will have the same MAC address as a bridge on the VLAN
1119              * device's physical network device.
1120              *
1121              * Handle this case by hashing the physical network device MAC
1122              * along with the VLAN identifier.
1123              */
1124             uint8_t buf[ETH_ADDR_LEN + 2];
1125             memcpy(buf, bridge_ea, ETH_ADDR_LEN);
1126             buf[ETH_ADDR_LEN] = vlan >> 8;
1127             buf[ETH_ADDR_LEN + 1] = vlan;
1128             return dpid_from_hash(buf, sizeof buf);
1129         } else {
1130             /*
1131              * Assume that this bridge's MAC address is unique, since it
1132              * doesn't fit any of the cases we handle specially.
1133              */
1134         }
1135     } else {
1136         /*
1137          * A purely internal bridge, that is, one that has no non-virtual
1138          * network devices on it at all, is more difficult because it has no
1139          * natural unique identifier at all.
1140          *
1141          * When the host is a XenServer, we handle this case by hashing the
1142          * host's UUID with the name of the bridge.  Names of bridges are
1143          * persistent across XenServer reboots, although they can be reused if
1144          * an internal network is destroyed and then a new one is later
1145          * created, so this is fairly effective.
1146          *
1147          * When the host is not a XenServer, we punt by using a random MAC
1148          * address on each run.
1149          */
1150         const char *host_uuid = xenserver_get_host_uuid();
1151         if (host_uuid) {
1152             char *combined = xasprintf("%s,%s", host_uuid, br->name);
1153             dpid = dpid_from_hash(combined, strlen(combined));
1154             free(combined);
1155             return dpid;
1156         }
1157     }
1158
1159     return eth_addr_to_uint64(bridge_ea);
1160 }
1161
1162 static uint64_t
1163 dpid_from_hash(const void *data, size_t n)
1164 {
1165     uint8_t hash[SHA1_DIGEST_SIZE];
1166
1167     BUILD_ASSERT_DECL(sizeof hash >= ETH_ADDR_LEN);
1168     sha1_bytes(data, n, hash);
1169     eth_addr_mark_random(hash);
1170     return eth_addr_to_uint64(hash);
1171 }
1172
1173 static void
1174 iface_refresh_status(struct iface *iface)
1175 {
1176     struct shash sh;
1177
1178     enum netdev_flags flags;
1179     uint32_t current;
1180     int64_t bps;
1181     int mtu;
1182     int64_t mtu_64;
1183     int error;
1184
1185     if (iface_is_synthetic(iface)) {
1186         return;
1187     }
1188
1189     shash_init(&sh);
1190
1191     if (!netdev_get_status(iface->netdev, &sh)) {
1192         size_t n;
1193         char **keys, **values;
1194
1195         shash_to_ovs_idl_map(&sh, &keys, &values, &n);
1196         ovsrec_interface_set_status(iface->cfg, keys, values, n);
1197
1198         free(keys);
1199         free(values);
1200     } else {
1201         ovsrec_interface_set_status(iface->cfg, NULL, NULL, 0);
1202     }
1203
1204     shash_destroy_free_data(&sh);
1205
1206     error = netdev_get_flags(iface->netdev, &flags);
1207     if (!error) {
1208         ovsrec_interface_set_admin_state(iface->cfg, flags & NETDEV_UP ? "up" : "down");
1209     }
1210     else {
1211         ovsrec_interface_set_admin_state(iface->cfg, NULL);
1212     }
1213
1214     error = netdev_get_features(iface->netdev, &current, NULL, NULL, NULL);
1215     if (!error) {
1216         ovsrec_interface_set_duplex(iface->cfg,
1217                                     netdev_features_is_full_duplex(current)
1218                                     ? "full" : "half");
1219         /* warning: uint64_t -> int64_t conversion */
1220         bps = netdev_features_to_bps(current);
1221         ovsrec_interface_set_link_speed(iface->cfg, &bps, 1);
1222     }
1223     else {
1224         ovsrec_interface_set_duplex(iface->cfg, NULL);
1225         ovsrec_interface_set_link_speed(iface->cfg, NULL, 0);
1226     }
1227
1228     ovsrec_interface_set_link_state(iface->cfg,
1229                                     iface_get_carrier(iface) ? "up" : "down");
1230
1231     error = netdev_get_mtu(iface->netdev, &mtu);
1232     if (!error && mtu != INT_MAX) {
1233         mtu_64 = mtu;
1234         ovsrec_interface_set_mtu(iface->cfg, &mtu_64, 1);
1235     }
1236     else {
1237         ovsrec_interface_set_mtu(iface->cfg, NULL, 0);
1238     }
1239 }
1240
1241 /* Writes 'iface''s CFM statistics to the database.  Returns true if anything
1242  * changed, false otherwise. */
1243 static bool
1244 iface_refresh_cfm_stats(struct iface *iface)
1245 {
1246     const struct ovsrec_monitor *mon;
1247     const struct cfm *cfm;
1248     bool changed = false;
1249     size_t i;
1250
1251     mon = iface->cfg->monitor;
1252     cfm = ofproto_port_get_cfm(iface->port->bridge->ofproto, iface->ofp_port);
1253
1254     if (!cfm || !mon) {
1255         return false;
1256     }
1257
1258     for (i = 0; i < mon->n_remote_mps; i++) {
1259         const struct ovsrec_maintenance_point *mp;
1260         const struct remote_mp *rmp;
1261
1262         mp = mon->remote_mps[i];
1263         rmp = cfm_get_remote_mp(cfm, mp->mpid);
1264
1265         if (mp->n_fault != 1 || mp->fault[0] != rmp->fault) {
1266             ovsrec_maintenance_point_set_fault(mp, &rmp->fault, 1);
1267             changed = true;
1268         }
1269     }
1270
1271     if (mon->n_fault != 1 || mon->fault[0] != cfm->fault) {
1272         ovsrec_monitor_set_fault(mon, &cfm->fault, 1);
1273         changed = true;
1274     }
1275
1276     return changed;
1277 }
1278
1279 static bool
1280 iface_refresh_lacp_stats(struct iface *iface)
1281 {
1282     struct ofproto *ofproto = iface->port->bridge->ofproto;
1283     int old = iface->cfg->lacp_current ? *iface->cfg->lacp_current : -1;
1284     int new = ofproto_port_is_lacp_current(ofproto, iface->ofp_port);
1285
1286     if (old != new) {
1287         bool current = new;
1288         ovsrec_interface_set_lacp_current(iface->cfg, &current, new >= 0);
1289     }
1290     return old != new;
1291 }
1292
1293 static void
1294 iface_refresh_stats(struct iface *iface)
1295 {
1296     struct iface_stat {
1297         char *name;
1298         int offset;
1299     };
1300     static const struct iface_stat iface_stats[] = {
1301         { "rx_packets", offsetof(struct netdev_stats, rx_packets) },
1302         { "tx_packets", offsetof(struct netdev_stats, tx_packets) },
1303         { "rx_bytes", offsetof(struct netdev_stats, rx_bytes) },
1304         { "tx_bytes", offsetof(struct netdev_stats, tx_bytes) },
1305         { "rx_dropped", offsetof(struct netdev_stats, rx_dropped) },
1306         { "tx_dropped", offsetof(struct netdev_stats, tx_dropped) },
1307         { "rx_errors", offsetof(struct netdev_stats, rx_errors) },
1308         { "tx_errors", offsetof(struct netdev_stats, tx_errors) },
1309         { "rx_frame_err", offsetof(struct netdev_stats, rx_frame_errors) },
1310         { "rx_over_err", offsetof(struct netdev_stats, rx_over_errors) },
1311         { "rx_crc_err", offsetof(struct netdev_stats, rx_crc_errors) },
1312         { "collisions", offsetof(struct netdev_stats, collisions) },
1313     };
1314     enum { N_STATS = ARRAY_SIZE(iface_stats) };
1315     const struct iface_stat *s;
1316
1317     char *keys[N_STATS];
1318     int64_t values[N_STATS];
1319     int n;
1320
1321     struct netdev_stats stats;
1322
1323     if (iface_is_synthetic(iface)) {
1324         return;
1325     }
1326
1327     /* Intentionally ignore return value, since errors will set 'stats' to
1328      * all-1s, and we will deal with that correctly below. */
1329     netdev_get_stats(iface->netdev, &stats);
1330
1331     n = 0;
1332     for (s = iface_stats; s < &iface_stats[N_STATS]; s++) {
1333         uint64_t value = *(uint64_t *) (((char *) &stats) + s->offset);
1334         if (value != UINT64_MAX) {
1335             keys[n] = s->name;
1336             values[n] = value;
1337             n++;
1338         }
1339     }
1340
1341     ovsrec_interface_set_statistics(iface->cfg, keys, values, n);
1342 }
1343
1344 static void
1345 refresh_system_stats(const struct ovsrec_open_vswitch *cfg)
1346 {
1347     struct ovsdb_datum datum;
1348     struct shash stats;
1349
1350     shash_init(&stats);
1351     get_system_stats(&stats);
1352
1353     ovsdb_datum_from_shash(&datum, &stats);
1354     ovsdb_idl_txn_write(&cfg->header_, &ovsrec_open_vswitch_col_statistics,
1355                         &datum);
1356 }
1357
1358 static inline const char *
1359 nx_role_to_str(enum nx_role role)
1360 {
1361     switch (role) {
1362     case NX_ROLE_OTHER:
1363         return "other";
1364     case NX_ROLE_MASTER:
1365         return "master";
1366     case NX_ROLE_SLAVE:
1367         return "slave";
1368     default:
1369         return "*** INVALID ROLE ***";
1370     }
1371 }
1372
1373 static void
1374 bridge_refresh_controller_status(const struct bridge *br)
1375 {
1376     struct shash info;
1377     const struct ovsrec_controller *cfg;
1378
1379     ofproto_get_ofproto_controller_info(br->ofproto, &info);
1380
1381     OVSREC_CONTROLLER_FOR_EACH(cfg, idl) {
1382         struct ofproto_controller_info *cinfo =
1383             shash_find_data(&info, cfg->target);
1384
1385         if (cinfo) {
1386             ovsrec_controller_set_is_connected(cfg, cinfo->is_connected);
1387             ovsrec_controller_set_role(cfg, nx_role_to_str(cinfo->role));
1388             ovsrec_controller_set_status(cfg, (char **) cinfo->pairs.keys,
1389                                          (char **) cinfo->pairs.values,
1390                                          cinfo->pairs.n);
1391         } else {
1392             ovsrec_controller_set_is_connected(cfg, false);
1393             ovsrec_controller_set_role(cfg, NULL);
1394             ovsrec_controller_set_status(cfg, NULL, NULL, 0);
1395         }
1396     }
1397
1398     ofproto_free_ofproto_controller_info(&info);
1399 }
1400
1401 void
1402 bridge_run(void)
1403 {
1404     const struct ovsrec_open_vswitch *cfg;
1405
1406     bool datapath_destroyed;
1407     bool database_changed;
1408     struct bridge *br;
1409
1410     /* Let each bridge do the work that it needs to do. */
1411     datapath_destroyed = false;
1412     HMAP_FOR_EACH (br, node, &all_bridges) {
1413         int error = ofproto_run(br->ofproto);
1414         if (error) {
1415             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
1416             VLOG_ERR_RL(&rl, "bridge %s: datapath was destroyed externally, "
1417                         "forcing reconfiguration", br->name);
1418             datapath_destroyed = true;
1419         }
1420     }
1421
1422     /* (Re)configure if necessary. */
1423     database_changed = ovsdb_idl_run(idl);
1424     cfg = ovsrec_open_vswitch_first(idl);
1425 #ifdef HAVE_OPENSSL
1426     /* Re-configure SSL.  We do this on every trip through the main loop,
1427      * instead of just when the database changes, because the contents of the
1428      * key and certificate files can change without the database changing.
1429      *
1430      * We do this before bridge_reconfigure() because that function might
1431      * initiate SSL connections and thus requires SSL to be configured. */
1432     if (cfg && cfg->ssl) {
1433         const struct ovsrec_ssl *ssl = cfg->ssl;
1434
1435         stream_ssl_set_key_and_cert(ssl->private_key, ssl->certificate);
1436         stream_ssl_set_ca_cert_file(ssl->ca_cert, ssl->bootstrap_ca_cert);
1437     }
1438 #endif
1439     if (database_changed || datapath_destroyed) {
1440         if (cfg) {
1441             struct ovsdb_idl_txn *txn = ovsdb_idl_txn_create(idl);
1442
1443             bridge_reconfigure(cfg);
1444
1445             ovsrec_open_vswitch_set_cur_cfg(cfg, cfg->next_cfg);
1446             ovsdb_idl_txn_commit(txn);
1447             ovsdb_idl_txn_destroy(txn); /* XXX */
1448         } else {
1449             /* We still need to reconfigure to avoid dangling pointers to
1450              * now-destroyed ovsrec structures inside bridge data. */
1451             static const struct ovsrec_open_vswitch null_cfg;
1452
1453             bridge_reconfigure(&null_cfg);
1454         }
1455     }
1456
1457     /* Refresh system and interface stats if necessary. */
1458     if (time_msec() >= stats_timer) {
1459         if (cfg) {
1460             struct ovsdb_idl_txn *txn;
1461
1462             txn = ovsdb_idl_txn_create(idl);
1463             HMAP_FOR_EACH (br, node, &all_bridges) {
1464                 struct port *port;
1465
1466                 HMAP_FOR_EACH (port, hmap_node, &br->ports) {
1467                     struct iface *iface;
1468
1469                     LIST_FOR_EACH (iface, port_elem, &port->ifaces) {
1470                         iface_refresh_stats(iface);
1471                         iface_refresh_status(iface);
1472                     }
1473                 }
1474                 bridge_refresh_controller_status(br);
1475             }
1476             refresh_system_stats(cfg);
1477             ovsdb_idl_txn_commit(txn);
1478             ovsdb_idl_txn_destroy(txn); /* XXX */
1479         }
1480
1481         stats_timer = time_msec() + STATS_INTERVAL;
1482     }
1483
1484     if (time_msec() >= db_limiter) {
1485         struct ovsdb_idl_txn *txn;
1486         bool changed = false;
1487
1488         txn = ovsdb_idl_txn_create(idl);
1489         HMAP_FOR_EACH (br, node, &all_bridges) {
1490             struct port *port;
1491
1492             HMAP_FOR_EACH (port, hmap_node, &br->ports) {
1493                 struct iface *iface;
1494
1495                 LIST_FOR_EACH (iface, port_elem, &port->ifaces) {
1496                     changed = iface_refresh_cfm_stats(iface) || changed;
1497                     changed = iface_refresh_lacp_stats(iface) || changed;
1498                 }
1499             }
1500         }
1501
1502         if (changed) {
1503             db_limiter = time_msec() + DB_LIMIT_INTERVAL;
1504         }
1505
1506         ovsdb_idl_txn_commit(txn);
1507         ovsdb_idl_txn_destroy(txn);
1508     }
1509 }
1510
1511 void
1512 bridge_wait(void)
1513 {
1514     struct bridge *br;
1515
1516     HMAP_FOR_EACH (br, node, &all_bridges) {
1517         ofproto_wait(br->ofproto);
1518     }
1519     ovsdb_idl_wait(idl);
1520     poll_timer_wait_until(stats_timer);
1521
1522     if (db_limiter > time_msec()) {
1523         poll_timer_wait_until(db_limiter);
1524     }
1525 }
1526 \f
1527 /* CFM unixctl user interface functions. */
1528 static void
1529 cfm_unixctl_show(struct unixctl_conn *conn,
1530                  const char *args, void *aux OVS_UNUSED)
1531 {
1532     struct ds ds = DS_EMPTY_INITIALIZER;
1533     struct iface *iface;
1534     const struct cfm *cfm;
1535
1536     iface = iface_find(args);
1537     if (!iface) {
1538         unixctl_command_reply(conn, 501, "no such interface");
1539         return;
1540     }
1541
1542     cfm = ofproto_port_get_cfm(iface->port->bridge->ofproto, iface->ofp_port);
1543
1544     if (!cfm) {
1545         unixctl_command_reply(conn, 501, "CFM not enabled");
1546         return;
1547     }
1548
1549     cfm_dump_ds(cfm, &ds);
1550     unixctl_command_reply(conn, 200, ds_cstr(&ds));
1551     ds_destroy(&ds);
1552 }
1553 \f
1554 /* QoS unixctl user interface functions. */
1555
1556 struct qos_unixctl_show_cbdata {
1557     struct ds *ds;
1558     struct iface *iface;
1559 };
1560
1561 static void
1562 qos_unixctl_show_cb(unsigned int queue_id,
1563                     const struct shash *details,
1564                     void *aux)
1565 {
1566     struct qos_unixctl_show_cbdata *data = aux;
1567     struct ds *ds = data->ds;
1568     struct iface *iface = data->iface;
1569     struct netdev_queue_stats stats;
1570     struct shash_node *node;
1571     int error;
1572
1573     ds_put_cstr(ds, "\n");
1574     if (queue_id) {
1575         ds_put_format(ds, "Queue %u:\n", queue_id);
1576     } else {
1577         ds_put_cstr(ds, "Default:\n");
1578     }
1579
1580     SHASH_FOR_EACH (node, details) {
1581         ds_put_format(ds, "\t%s: %s\n", node->name, (char *)node->data);
1582     }
1583
1584     error = netdev_get_queue_stats(iface->netdev, queue_id, &stats);
1585     if (!error) {
1586         if (stats.tx_packets != UINT64_MAX) {
1587             ds_put_format(ds, "\ttx_packets: %"PRIu64"\n", stats.tx_packets);
1588         }
1589
1590         if (stats.tx_bytes != UINT64_MAX) {
1591             ds_put_format(ds, "\ttx_bytes: %"PRIu64"\n", stats.tx_bytes);
1592         }
1593
1594         if (stats.tx_errors != UINT64_MAX) {
1595             ds_put_format(ds, "\ttx_errors: %"PRIu64"\n", stats.tx_errors);
1596         }
1597     } else {
1598         ds_put_format(ds, "\tFailed to get statistics for queue %u: %s",
1599                       queue_id, strerror(error));
1600     }
1601 }
1602
1603 static void
1604 qos_unixctl_show(struct unixctl_conn *conn,
1605                  const char *args, void *aux OVS_UNUSED)
1606 {
1607     struct ds ds = DS_EMPTY_INITIALIZER;
1608     struct shash sh = SHASH_INITIALIZER(&sh);
1609     struct iface *iface;
1610     const char *type;
1611     struct shash_node *node;
1612     struct qos_unixctl_show_cbdata data;
1613     int error;
1614
1615     iface = iface_find(args);
1616     if (!iface) {
1617         unixctl_command_reply(conn, 501, "no such interface");
1618         return;
1619     }
1620
1621     netdev_get_qos(iface->netdev, &type, &sh);
1622
1623     if (*type != '\0') {
1624         ds_put_format(&ds, "QoS: %s %s\n", iface->name, type);
1625
1626         SHASH_FOR_EACH (node, &sh) {
1627             ds_put_format(&ds, "%s: %s\n", node->name, (char *)node->data);
1628         }
1629
1630         data.ds = &ds;
1631         data.iface = iface;
1632         error = netdev_dump_queues(iface->netdev, qos_unixctl_show_cb, &data);
1633
1634         if (error) {
1635             ds_put_format(&ds, "failed to dump queues: %s", strerror(error));
1636         }
1637         unixctl_command_reply(conn, 200, ds_cstr(&ds));
1638     } else {
1639         ds_put_format(&ds, "QoS not configured on %s\n", iface->name);
1640         unixctl_command_reply(conn, 501, ds_cstr(&ds));
1641     }
1642
1643     shash_destroy_free_data(&sh);
1644     ds_destroy(&ds);
1645 }
1646 \f
1647 /* Bridge reconfiguration functions. */
1648 static void
1649 bridge_create(const struct ovsrec_bridge *br_cfg)
1650 {
1651     struct bridge *br;
1652
1653     assert(!bridge_lookup(br_cfg->name));
1654     br = xzalloc(sizeof *br);
1655
1656     br->name = xstrdup(br_cfg->name);
1657     br->type = xstrdup(dpif_normalize_type(br_cfg->datapath_type));
1658     br->cfg = br_cfg;
1659     eth_addr_nicira_random(br->default_ea);
1660
1661     hmap_init(&br->ports);
1662     hmap_init(&br->ifaces);
1663     hmap_init(&br->iface_by_name);
1664     hmap_init(&br->mirrors);
1665
1666     hmap_insert(&all_bridges, &br->node, hash_string(br->name, 0));
1667 }
1668
1669 static void
1670 bridge_destroy(struct bridge *br)
1671 {
1672     if (br) {
1673         struct mirror *mirror, *next_mirror;
1674         struct port *port, *next_port;
1675
1676         HMAP_FOR_EACH_SAFE (port, next_port, hmap_node, &br->ports) {
1677             port_destroy(port);
1678         }
1679         HMAP_FOR_EACH_SAFE (mirror, next_mirror, hmap_node, &br->mirrors) {
1680             mirror_destroy(mirror);
1681         }
1682         hmap_remove(&all_bridges, &br->node);
1683         ofproto_destroy(br->ofproto);
1684         hmap_destroy(&br->ifaces);
1685         hmap_destroy(&br->ports);
1686         hmap_destroy(&br->iface_by_name);
1687         hmap_destroy(&br->mirrors);
1688         free(br->name);
1689         free(br->type);
1690         free(br);
1691     }
1692 }
1693
1694 static struct bridge *
1695 bridge_lookup(const char *name)
1696 {
1697     struct bridge *br;
1698
1699     HMAP_FOR_EACH_WITH_HASH (br, node, hash_string(name, 0), &all_bridges) {
1700         if (!strcmp(br->name, name)) {
1701             return br;
1702         }
1703     }
1704     return NULL;
1705 }
1706
1707 /* Handle requests for a listing of all flows known by the OpenFlow
1708  * stack, including those normally hidden. */
1709 static void
1710 bridge_unixctl_dump_flows(struct unixctl_conn *conn,
1711                           const char *args, void *aux OVS_UNUSED)
1712 {
1713     struct bridge *br;
1714     struct ds results;
1715
1716     br = bridge_lookup(args);
1717     if (!br) {
1718         unixctl_command_reply(conn, 501, "Unknown bridge");
1719         return;
1720     }
1721
1722     ds_init(&results);
1723     ofproto_get_all_flows(br->ofproto, &results);
1724
1725     unixctl_command_reply(conn, 200, ds_cstr(&results));
1726     ds_destroy(&results);
1727 }
1728
1729 /* "bridge/reconnect [BRIDGE]": makes BRIDGE drop all of its controller
1730  * connections and reconnect.  If BRIDGE is not specified, then all bridges
1731  * drop their controller connections and reconnect. */
1732 static void
1733 bridge_unixctl_reconnect(struct unixctl_conn *conn,
1734                          const char *args, void *aux OVS_UNUSED)
1735 {
1736     struct bridge *br;
1737     if (args[0] != '\0') {
1738         br = bridge_lookup(args);
1739         if (!br) {
1740             unixctl_command_reply(conn, 501, "Unknown bridge");
1741             return;
1742         }
1743         ofproto_reconnect_controllers(br->ofproto);
1744     } else {
1745         HMAP_FOR_EACH (br, node, &all_bridges) {
1746             ofproto_reconnect_controllers(br->ofproto);
1747         }
1748     }
1749     unixctl_command_reply(conn, 200, NULL);
1750 }
1751
1752 static size_t
1753 bridge_get_controllers(const struct bridge *br,
1754                        struct ovsrec_controller ***controllersp)
1755 {
1756     struct ovsrec_controller **controllers;
1757     size_t n_controllers;
1758
1759     controllers = br->cfg->controller;
1760     n_controllers = br->cfg->n_controller;
1761
1762     if (n_controllers == 1 && !strcmp(controllers[0]->target, "none")) {
1763         controllers = NULL;
1764         n_controllers = 0;
1765     }
1766
1767     if (controllersp) {
1768         *controllersp = controllers;
1769     }
1770     return n_controllers;
1771 }
1772
1773 /* Adds and deletes "struct port"s and "struct iface"s under 'br' to match
1774  * those configured in 'br->cfg'. */
1775 static void
1776 bridge_add_del_ports(struct bridge *br)
1777 {
1778     struct port *port, *next;
1779     struct shash_node *node;
1780     struct shash new_ports;
1781     size_t i;
1782
1783     /* Collect new ports. */
1784     shash_init(&new_ports);
1785     for (i = 0; i < br->cfg->n_ports; i++) {
1786         const char *name = br->cfg->ports[i]->name;
1787         if (!shash_add_once(&new_ports, name, br->cfg->ports[i])) {
1788             VLOG_WARN("bridge %s: %s specified twice as bridge port",
1789                       br->name, name);
1790         }
1791     }
1792     if (bridge_get_controllers(br, NULL)
1793         && !shash_find(&new_ports, br->name)) {
1794         VLOG_WARN("bridge %s: no port named %s, synthesizing one",
1795                   br->name, br->name);
1796
1797         br->synth_local_port.interfaces = &br->synth_local_ifacep;
1798         br->synth_local_port.n_interfaces = 1;
1799         br->synth_local_port.name = br->name;
1800
1801         br->synth_local_iface.name = br->name;
1802         br->synth_local_iface.type = "internal";
1803
1804         br->synth_local_ifacep = &br->synth_local_iface;
1805
1806         shash_add(&new_ports, br->name, &br->synth_local_port);
1807     }
1808
1809     /* Get rid of deleted ports.
1810      * Get rid of deleted interfaces on ports that still exist.
1811      * Update 'cfg' of ports that still exist. */
1812     HMAP_FOR_EACH_SAFE (port, next, hmap_node, &br->ports) {
1813         port->cfg = shash_find_data(&new_ports, port->name);
1814         if (!port->cfg) {
1815             port_destroy(port);
1816         } else {
1817             port_del_ifaces(port);
1818         }
1819     }
1820
1821     /* Create new ports.
1822      * Add new interfaces to existing ports. */
1823     SHASH_FOR_EACH (node, &new_ports) {
1824         struct port *port = port_lookup(br, node->name);
1825         if (!port) {
1826             struct ovsrec_port *cfg = node->data;
1827             port = port_create(br, cfg);
1828         }
1829         port_add_ifaces(port);
1830         if (list_is_empty(&port->ifaces)) {
1831             VLOG_WARN("bridge %s: port %s has no interfaces, dropping",
1832                       br->name, port->name);
1833             port_destroy(port);
1834         }
1835     }
1836     shash_destroy(&new_ports);
1837 }
1838
1839 /* Initializes 'oc' appropriately as a management service controller for
1840  * 'br'.
1841  *
1842  * The caller must free oc->target when it is no longer needed. */
1843 static void
1844 bridge_ofproto_controller_for_mgmt(const struct bridge *br,
1845                                    struct ofproto_controller *oc)
1846 {
1847     oc->target = xasprintf("punix:%s/%s.mgmt", ovs_rundir(), br->name);
1848     oc->max_backoff = 0;
1849     oc->probe_interval = 60;
1850     oc->band = OFPROTO_OUT_OF_BAND;
1851     oc->rate_limit = 0;
1852     oc->burst_limit = 0;
1853 }
1854
1855 /* Converts ovsrec_controller 'c' into an ofproto_controller in 'oc'.  */
1856 static void
1857 bridge_ofproto_controller_from_ovsrec(const struct ovsrec_controller *c,
1858                                       struct ofproto_controller *oc)
1859 {
1860     oc->target = c->target;
1861     oc->max_backoff = c->max_backoff ? *c->max_backoff / 1000 : 8;
1862     oc->probe_interval = c->inactivity_probe ? *c->inactivity_probe / 1000 : 5;
1863     oc->band = (!c->connection_mode || !strcmp(c->connection_mode, "in-band")
1864                 ? OFPROTO_IN_BAND : OFPROTO_OUT_OF_BAND);
1865     oc->rate_limit = c->controller_rate_limit ? *c->controller_rate_limit : 0;
1866     oc->burst_limit = (c->controller_burst_limit
1867                        ? *c->controller_burst_limit : 0);
1868 }
1869
1870 /* Configures the IP stack for 'br''s local interface properly according to the
1871  * configuration in 'c'.  */
1872 static void
1873 bridge_configure_local_iface_netdev(struct bridge *br,
1874                                     struct ovsrec_controller *c)
1875 {
1876     struct netdev *netdev;
1877     struct in_addr mask, gateway;
1878
1879     struct iface *local_iface;
1880     struct in_addr ip;
1881
1882     /* If there's no local interface or no IP address, give up. */
1883     local_iface = iface_from_ofp_port(br, OFPP_LOCAL);
1884     if (!local_iface || !c->local_ip || !inet_aton(c->local_ip, &ip)) {
1885         return;
1886     }
1887
1888     /* Bring up the local interface. */
1889     netdev = local_iface->netdev;
1890     netdev_turn_flags_on(netdev, NETDEV_UP, true);
1891
1892     /* Configure the IP address and netmask. */
1893     if (!c->local_netmask
1894         || !inet_aton(c->local_netmask, &mask)
1895         || !mask.s_addr) {
1896         mask.s_addr = guess_netmask(ip.s_addr);
1897     }
1898     if (!netdev_set_in4(netdev, ip, mask)) {
1899         VLOG_INFO("bridge %s: configured IP address "IP_FMT", netmask "IP_FMT,
1900                   br->name, IP_ARGS(&ip.s_addr), IP_ARGS(&mask.s_addr));
1901     }
1902
1903     /* Configure the default gateway. */
1904     if (c->local_gateway
1905         && inet_aton(c->local_gateway, &gateway)
1906         && gateway.s_addr) {
1907         if (!netdev_add_router(netdev, gateway)) {
1908             VLOG_INFO("bridge %s: configured gateway "IP_FMT,
1909                       br->name, IP_ARGS(&gateway.s_addr));
1910         }
1911     }
1912 }
1913
1914 static void
1915 bridge_configure_remotes(struct bridge *br,
1916                          const struct sockaddr_in *managers, size_t n_managers)
1917 {
1918     const char *disable_ib_str, *queue_id_str;
1919     bool disable_in_band = false;
1920     int queue_id;
1921
1922     struct ovsrec_controller **controllers;
1923     size_t n_controllers;
1924
1925     enum ofproto_fail_mode fail_mode;
1926
1927     struct ofproto_controller *ocs;
1928     size_t n_ocs;
1929     size_t i;
1930
1931     /* Check if we should disable in-band control on this bridge. */
1932     disable_ib_str = bridge_get_other_config(br->cfg, "disable-in-band");
1933     if (disable_ib_str && !strcmp(disable_ib_str, "true")) {
1934         disable_in_band = true;
1935     }
1936
1937     /* Set OpenFlow queue ID for in-band control. */
1938     queue_id_str = bridge_get_other_config(br->cfg, "in-band-queue");
1939     queue_id = queue_id_str ? strtol(queue_id_str, NULL, 10) : -1;
1940     ofproto_set_in_band_queue(br->ofproto, queue_id);
1941
1942     if (disable_in_band) {
1943         ofproto_set_extra_in_band_remotes(br->ofproto, NULL, 0);
1944     } else {
1945         ofproto_set_extra_in_band_remotes(br->ofproto, managers, n_managers);
1946     }
1947
1948     n_controllers = bridge_get_controllers(br, &controllers);
1949
1950     ocs = xmalloc((n_controllers + 1) * sizeof *ocs);
1951     n_ocs = 0;
1952
1953     bridge_ofproto_controller_for_mgmt(br, &ocs[n_ocs++]);
1954     for (i = 0; i < n_controllers; i++) {
1955         struct ovsrec_controller *c = controllers[i];
1956
1957         if (!strncmp(c->target, "punix:", 6)
1958             || !strncmp(c->target, "unix:", 5)) {
1959             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
1960
1961             /* Prevent remote ovsdb-server users from accessing arbitrary Unix
1962              * domain sockets and overwriting arbitrary local files. */
1963             VLOG_ERR_RL(&rl, "bridge %s: not adding Unix domain socket "
1964                         "controller \"%s\" due to possibility for remote "
1965                         "exploit", br->name, c->target);
1966             continue;
1967         }
1968
1969         bridge_configure_local_iface_netdev(br, c);
1970         bridge_ofproto_controller_from_ovsrec(c, &ocs[n_ocs]);
1971         if (disable_in_band) {
1972             ocs[n_ocs].band = OFPROTO_OUT_OF_BAND;
1973         }
1974         n_ocs++;
1975     }
1976
1977     ofproto_set_controllers(br->ofproto, ocs, n_ocs);
1978     free(ocs[0].target); /* From bridge_ofproto_controller_for_mgmt(). */
1979     free(ocs);
1980
1981     /* Set the fail-mode. */
1982     fail_mode = !br->cfg->fail_mode
1983                 || !strcmp(br->cfg->fail_mode, "standalone")
1984                     ? OFPROTO_FAIL_STANDALONE
1985                     : OFPROTO_FAIL_SECURE;
1986     ofproto_set_fail_mode(br->ofproto, fail_mode);
1987
1988     /* Configure OpenFlow controller connection snooping. */
1989     if (!ofproto_has_snoops(br->ofproto)) {
1990         struct sset snoops;
1991
1992         sset_init(&snoops);
1993         sset_add_and_free(&snoops, xasprintf("punix:%s/%s.snoop",
1994                                              ovs_rundir(), br->name));
1995         ofproto_set_snoops(br->ofproto, &snoops);
1996         sset_destroy(&snoops);
1997     }
1998 }
1999 \f
2000 /* Port functions. */
2001
2002 static struct port *
2003 port_create(struct bridge *br, const struct ovsrec_port *cfg)
2004 {
2005     struct port *port;
2006
2007     port = xzalloc(sizeof *port);
2008     port->bridge = br;
2009     port->name = xstrdup(cfg->name);
2010     port->cfg = cfg;
2011     list_init(&port->ifaces);
2012
2013     hmap_insert(&br->ports, &port->hmap_node, hash_string(port->name, 0));
2014
2015     VLOG_INFO("created port %s on bridge %s", port->name, br->name);
2016
2017     return port;
2018 }
2019
2020 static const char *
2021 get_port_other_config(const struct ovsrec_port *port, const char *key,
2022                       const char *default_value)
2023 {
2024     const char *value;
2025
2026     value = get_ovsrec_key_value(&port->header_, &ovsrec_port_col_other_config,
2027                                  key);
2028     return value ? value : default_value;
2029 }
2030
2031 static const char *
2032 get_interface_other_config(const struct ovsrec_interface *iface,
2033                            const char *key, const char *default_value)
2034 {
2035     const char *value;
2036
2037     value = get_ovsrec_key_value(&iface->header_,
2038                                  &ovsrec_interface_col_other_config, key);
2039     return value ? value : default_value;
2040 }
2041
2042 /* Deletes interfaces from 'port' that are no longer configured for it. */
2043 static void
2044 port_del_ifaces(struct port *port)
2045 {
2046     struct iface *iface, *next;
2047     struct sset new_ifaces;
2048     size_t i;
2049
2050     /* Collect list of new interfaces. */
2051     sset_init(&new_ifaces);
2052     for (i = 0; i < port->cfg->n_interfaces; i++) {
2053         const char *name = port->cfg->interfaces[i]->name;
2054         sset_add(&new_ifaces, name);
2055     }
2056
2057     /* Get rid of deleted interfaces. */
2058     LIST_FOR_EACH_SAFE (iface, next, port_elem, &port->ifaces) {
2059         if (!sset_contains(&new_ifaces, iface->name)) {
2060             iface_destroy(iface);
2061         }
2062     }
2063
2064     sset_destroy(&new_ifaces);
2065 }
2066
2067 /* Adds new interfaces to 'port' and updates 'type' and 'cfg' members of
2068  * existing ones. */
2069 static void
2070 port_add_ifaces(struct port *port)
2071 {
2072     struct shash new_ifaces;
2073     struct shash_node *node;
2074     size_t i;
2075
2076     /* Collect new ifaces. */
2077     shash_init(&new_ifaces);
2078     for (i = 0; i < port->cfg->n_interfaces; i++) {
2079         const struct ovsrec_interface *cfg = port->cfg->interfaces[i];
2080         if (!shash_add_once(&new_ifaces, cfg->name, cfg)) {
2081             VLOG_WARN("port %s: %s specified twice as port interface",
2082                       port->name, cfg->name);
2083             iface_set_ofport(cfg, -1);
2084         }
2085     }
2086
2087     /* Create new interfaces.
2088      * Update interface types and 'cfg' members. */
2089     SHASH_FOR_EACH (node, &new_ifaces) {
2090         const struct ovsrec_interface *cfg = node->data;
2091         const char *iface_name = node->name;
2092         struct iface *iface;
2093
2094         iface = iface_lookup(port->bridge, iface_name);
2095         if (!iface) {
2096             iface = iface_create(port, cfg);
2097         } else {
2098             iface->cfg = cfg;
2099         }
2100
2101         /* Determine interface type.  The local port always has type
2102          * "internal".  Other ports take their type from the database and
2103          * default to "system" if none is specified. */
2104         iface->type = (!strcmp(iface_name, port->bridge->name) ? "internal"
2105                        : cfg->type[0] ? cfg->type
2106                        : "system");
2107     }
2108     shash_destroy(&new_ifaces);
2109 }
2110
2111 static void
2112 port_destroy(struct port *port)
2113 {
2114     if (port) {
2115         struct bridge *br = port->bridge;
2116         struct iface *iface, *next;
2117
2118         if (br->ofproto) {
2119             ofproto_bundle_unregister(br->ofproto, port);
2120         }
2121
2122         LIST_FOR_EACH_SAFE (iface, next, port_elem, &port->ifaces) {
2123             iface_destroy(iface);
2124         }
2125
2126         hmap_remove(&br->ports, &port->hmap_node);
2127
2128         VLOG_INFO("destroyed port %s on bridge %s", port->name, br->name);
2129
2130         free(port->name);
2131         free(port);
2132     }
2133 }
2134
2135 static struct port *
2136 port_lookup(const struct bridge *br, const char *name)
2137 {
2138     struct port *port;
2139
2140     HMAP_FOR_EACH_WITH_HASH (port, hmap_node, hash_string(name, 0),
2141                              &br->ports) {
2142         if (!strcmp(port->name, name)) {
2143             return port;
2144         }
2145     }
2146     return NULL;
2147 }
2148
2149 static bool
2150 enable_lacp(struct port *port, bool *activep)
2151 {
2152     if (!port->cfg->lacp) {
2153         /* XXX when LACP implementation has been sufficiently tested, enable by
2154          * default and make active on bonded ports. */
2155         return false;
2156     } else if (!strcmp(port->cfg->lacp, "off")) {
2157         return false;
2158     } else if (!strcmp(port->cfg->lacp, "active")) {
2159         *activep = true;
2160         return true;
2161     } else if (!strcmp(port->cfg->lacp, "passive")) {
2162         *activep = false;
2163         return true;
2164     } else {
2165         VLOG_WARN("port %s: unknown LACP mode %s",
2166                   port->name, port->cfg->lacp);
2167         return false;
2168     }
2169 }
2170
2171 static struct lacp_settings *
2172 port_configure_lacp(struct port *port, struct lacp_settings *s)
2173 {
2174     const char *lacp_time;
2175     long long int custom_time;
2176     int priority;
2177
2178     if (!enable_lacp(port, &s->active)) {
2179         return NULL;
2180     }
2181
2182     s->name = port->name;
2183     memcpy(s->id, port->bridge->ea, ETH_ADDR_LEN);
2184
2185     /* Prefer bondable links if unspecified. */
2186     priority = atoi(get_port_other_config(port->cfg, "lacp-system-priority",
2187                                           "0"));
2188     s->priority = (priority > 0 && priority <= UINT16_MAX
2189                    ? priority
2190                    : UINT16_MAX - !list_is_short(&port->ifaces));
2191
2192     s->strict = !strcmp(get_port_other_config(port->cfg, "lacp-strict",
2193                                               "false"),
2194                         "true");
2195
2196     lacp_time = get_port_other_config(port->cfg, "lacp-time", "slow");
2197     custom_time = atoi(lacp_time);
2198     if (!strcmp(lacp_time, "fast")) {
2199         s->lacp_time = LACP_TIME_FAST;
2200     } else if (!strcmp(lacp_time, "slow")) {
2201         s->lacp_time = LACP_TIME_SLOW;
2202     } else if (custom_time > 0) {
2203         s->lacp_time = LACP_TIME_CUSTOM;
2204         s->custom_time = custom_time;
2205     } else {
2206         s->lacp_time = LACP_TIME_SLOW;
2207     }
2208
2209     return s;
2210 }
2211
2212 static void
2213 iface_configure_lacp(struct iface *iface, struct lacp_slave_settings *s)
2214 {
2215     int priority, portid;
2216
2217     portid = atoi(get_interface_other_config(iface->cfg, "lacp-port-id", "0"));
2218     priority = atoi(get_interface_other_config(iface->cfg,
2219                                                "lacp-port-priority", "0"));
2220
2221     if (portid <= 0 || portid > UINT16_MAX) {
2222         portid = iface->ofp_port;
2223     }
2224
2225     if (priority <= 0 || priority > UINT16_MAX) {
2226         priority = UINT16_MAX;
2227     }
2228
2229     s->name = iface->name;
2230     s->id = portid;
2231     s->priority = priority;
2232 }
2233
2234 static void
2235 port_configure_bond(struct port *port, struct bond_settings *s)
2236 {
2237     const char *detect_s;
2238
2239     s->name = port->name;
2240     s->balance = BM_SLB;
2241     if (port->cfg->bond_mode
2242         && !bond_mode_from_string(&s->balance, port->cfg->bond_mode)) {
2243         VLOG_WARN("port %s: unknown bond_mode %s, defaulting to %s",
2244                   port->name, port->cfg->bond_mode,
2245                   bond_mode_to_string(s->balance));
2246     }
2247
2248     s->detect = BLSM_CARRIER;
2249     detect_s = get_port_other_config(port->cfg, "bond-detect-mode", NULL);
2250     if (detect_s && !bond_detect_mode_from_string(&s->detect, detect_s)) {
2251         VLOG_WARN("port %s: unsupported bond-detect-mode %s, "
2252                   "defaulting to %s",
2253                   port->name, detect_s, bond_detect_mode_to_string(s->detect));
2254     }
2255
2256     s->miimon_interval = atoi(
2257         get_port_other_config(port->cfg, "bond-miimon-interval", "200"));
2258     if (s->miimon_interval < 100) {
2259         s->miimon_interval = 100;
2260     }
2261
2262     s->up_delay = MAX(0, port->cfg->bond_updelay);
2263     s->down_delay = MAX(0, port->cfg->bond_downdelay);
2264     s->rebalance_interval = atoi(
2265         get_port_other_config(port->cfg, "bond-rebalance-interval", "10000"));
2266     if (s->rebalance_interval < 1000) {
2267         s->rebalance_interval = 1000;
2268     }
2269
2270     s->fake_iface = port->cfg->bond_fake_iface;
2271 }
2272 \f
2273 /* Interface functions. */
2274
2275 static struct iface *
2276 iface_create(struct port *port, const struct ovsrec_interface *if_cfg)
2277 {
2278     struct bridge *br = port->bridge;
2279     struct iface *iface;
2280     char *name = if_cfg->name;
2281
2282     iface = xzalloc(sizeof *iface);
2283     iface->port = port;
2284     iface->name = xstrdup(name);
2285     iface->ofp_port = -1;
2286     iface->tag = tag_create_random();
2287     iface->netdev = NULL;
2288     iface->cfg = if_cfg;
2289
2290     hmap_insert(&br->iface_by_name, &iface->name_node, hash_string(name, 0));
2291
2292     list_push_back(&port->ifaces, &iface->port_elem);
2293
2294     VLOG_DBG("attached network device %s to port %s", iface->name, port->name);
2295
2296     return iface;
2297 }
2298
2299 static void
2300 iface_destroy(struct iface *iface)
2301 {
2302     if (iface) {
2303         struct port *port = iface->port;
2304         struct bridge *br = port->bridge;
2305
2306         if (br->ofproto && iface->ofp_port >= 0) {
2307             ofproto_port_unregister(br->ofproto, iface->ofp_port);
2308         }
2309
2310         if (iface->ofp_port >= 0) {
2311             hmap_remove(&br->ifaces, &iface->ofp_port_node);
2312         }
2313
2314         list_remove(&iface->port_elem);
2315         hmap_remove(&br->iface_by_name, &iface->name_node);
2316
2317         netdev_close(iface->netdev);
2318
2319         free(iface->name);
2320         free(iface);
2321     }
2322 }
2323
2324 static struct iface *
2325 iface_lookup(const struct bridge *br, const char *name)
2326 {
2327     struct iface *iface;
2328
2329     HMAP_FOR_EACH_WITH_HASH (iface, name_node, hash_string(name, 0),
2330                              &br->iface_by_name) {
2331         if (!strcmp(iface->name, name)) {
2332             return iface;
2333         }
2334     }
2335
2336     return NULL;
2337 }
2338
2339 static struct iface *
2340 iface_find(const char *name)
2341 {
2342     const struct bridge *br;
2343
2344     HMAP_FOR_EACH (br, node, &all_bridges) {
2345         struct iface *iface = iface_lookup(br, name);
2346
2347         if (iface) {
2348             return iface;
2349         }
2350     }
2351     return NULL;
2352 }
2353
2354 static struct iface *
2355 iface_from_ofp_port(const struct bridge *br, uint16_t ofp_port)
2356 {
2357     struct iface *iface;
2358
2359     HMAP_FOR_EACH_IN_BUCKET (iface, ofp_port_node,
2360                              hash_int(ofp_port, 0), &br->ifaces) {
2361         if (iface->ofp_port == ofp_port) {
2362             return iface;
2363         }
2364     }
2365     return NULL;
2366 }
2367
2368 /* Set Ethernet address of 'iface', if one is specified in the configuration
2369  * file. */
2370 static void
2371 iface_set_mac(struct iface *iface)
2372 {
2373     uint8_t ea[ETH_ADDR_LEN];
2374
2375     if (!strcmp(iface->type, "internal")
2376         && iface->cfg->mac && eth_addr_from_string(iface->cfg->mac, ea)) {
2377         if (iface->ofp_port == OFPP_LOCAL) {
2378             VLOG_ERR("interface %s: ignoring mac in Interface record "
2379                      "(use Bridge record to set local port's mac)",
2380                      iface->name);
2381         } else if (eth_addr_is_multicast(ea)) {
2382             VLOG_ERR("interface %s: cannot set MAC to multicast address",
2383                      iface->name);
2384         } else {
2385             int error = netdev_set_etheraddr(iface->netdev, ea);
2386             if (error) {
2387                 VLOG_ERR("interface %s: setting MAC failed (%s)",
2388                          iface->name, strerror(error));
2389             }
2390         }
2391     }
2392 }
2393
2394 /* Sets the ofport column of 'if_cfg' to 'ofport'. */
2395 static void
2396 iface_set_ofport(const struct ovsrec_interface *if_cfg, int64_t ofport)
2397 {
2398     if (if_cfg && !ovsdb_idl_row_is_synthetic(&if_cfg->header_)) {
2399         ovsrec_interface_set_ofport(if_cfg, &ofport, 1);
2400     }
2401 }
2402
2403 /* Adds the 'n' key-value pairs in 'keys' in 'values' to 'shash'.
2404  *
2405  * The value strings in '*shash' are taken directly from values[], not copied,
2406  * so the caller should not modify or free them. */
2407 static void
2408 shash_from_ovs_idl_map(char **keys, char **values, size_t n,
2409                        struct shash *shash)
2410 {
2411     size_t i;
2412
2413     shash_init(shash);
2414     for (i = 0; i < n; i++) {
2415         shash_add(shash, keys[i], values[i]);
2416     }
2417 }
2418
2419 /* Creates 'keys' and 'values' arrays from 'shash'.
2420  *
2421  * Sets 'keys' and 'values' to heap allocated arrays representing the key-value
2422  * pairs in 'shash'.  The caller takes ownership of 'keys' and 'values'.  They
2423  * are populated with with strings taken directly from 'shash' and thus have
2424  * the same ownership of the key-value pairs in shash.
2425  */
2426 static void
2427 shash_to_ovs_idl_map(struct shash *shash,
2428                      char ***keys, char ***values, size_t *n)
2429 {
2430     size_t i, count;
2431     char **k, **v;
2432     struct shash_node *sn;
2433
2434     count = shash_count(shash);
2435
2436     k = xmalloc(count * sizeof *k);
2437     v = xmalloc(count * sizeof *v);
2438
2439     i = 0;
2440     SHASH_FOR_EACH(sn, shash) {
2441         k[i] = sn->name;
2442         v[i] = sn->data;
2443         i++;
2444     }
2445
2446     *n      = count;
2447     *keys   = k;
2448     *values = v;
2449 }
2450
2451 struct iface_delete_queues_cbdata {
2452     struct netdev *netdev;
2453     const struct ovsdb_datum *queues;
2454 };
2455
2456 static bool
2457 queue_ids_include(const struct ovsdb_datum *queues, int64_t target)
2458 {
2459     union ovsdb_atom atom;
2460
2461     atom.integer = target;
2462     return ovsdb_datum_find_key(queues, &atom, OVSDB_TYPE_INTEGER) != UINT_MAX;
2463 }
2464
2465 static void
2466 iface_delete_queues(unsigned int queue_id,
2467                     const struct shash *details OVS_UNUSED, void *cbdata_)
2468 {
2469     struct iface_delete_queues_cbdata *cbdata = cbdata_;
2470
2471     if (!queue_ids_include(cbdata->queues, queue_id)) {
2472         netdev_delete_queue(cbdata->netdev, queue_id);
2473     }
2474 }
2475
2476 static void
2477 iface_configure_qos(struct iface *iface, const struct ovsrec_qos *qos)
2478 {
2479     if (!qos || qos->type[0] == '\0') {
2480         netdev_set_qos(iface->netdev, NULL, NULL);
2481     } else {
2482         struct iface_delete_queues_cbdata cbdata;
2483         struct shash details;
2484         size_t i;
2485
2486         /* Configure top-level Qos for 'iface'. */
2487         shash_from_ovs_idl_map(qos->key_other_config, qos->value_other_config,
2488                                qos->n_other_config, &details);
2489         netdev_set_qos(iface->netdev, qos->type, &details);
2490         shash_destroy(&details);
2491
2492         /* Deconfigure queues that were deleted. */
2493         cbdata.netdev = iface->netdev;
2494         cbdata.queues = ovsrec_qos_get_queues(qos, OVSDB_TYPE_INTEGER,
2495                                               OVSDB_TYPE_UUID);
2496         netdev_dump_queues(iface->netdev, iface_delete_queues, &cbdata);
2497
2498         /* Configure queues for 'iface'. */
2499         for (i = 0; i < qos->n_queues; i++) {
2500             const struct ovsrec_queue *queue = qos->value_queues[i];
2501             unsigned int queue_id = qos->key_queues[i];
2502
2503             shash_from_ovs_idl_map(queue->key_other_config,
2504                                    queue->value_other_config,
2505                                    queue->n_other_config, &details);
2506             netdev_set_queue(iface->netdev, queue_id, &details);
2507             shash_destroy(&details);
2508         }
2509     }
2510
2511     netdev_set_policing(iface->netdev,
2512                         iface->cfg->ingress_policing_rate,
2513                         iface->cfg->ingress_policing_burst);
2514 }
2515
2516 static void
2517 iface_configure_cfm(struct iface *iface)
2518 {
2519     size_t i;
2520     struct cfm cfm;
2521     uint16_t *remote_mps;
2522     struct ovsrec_monitor *mon;
2523     uint8_t maid[CCM_MAID_LEN];
2524
2525     mon = iface->cfg->monitor;
2526
2527     if (!mon) {
2528         ofproto_port_clear_cfm(iface->port->bridge->ofproto, iface->ofp_port);
2529         return;
2530     }
2531
2532     if (!cfm_generate_maid(mon->md_name, mon->ma_name, maid)) {
2533         VLOG_WARN("interface %s: Failed to generate MAID.", iface->name);
2534         return;
2535     }
2536
2537     cfm.mpid     = mon->mpid;
2538     cfm.interval = mon->interval ? *mon->interval : 1000;
2539
2540     memcpy(cfm.maid, maid, sizeof cfm.maid);
2541
2542     remote_mps = xzalloc(mon->n_remote_mps * sizeof *remote_mps);
2543     for(i = 0; i < mon->n_remote_mps; i++) {
2544         remote_mps[i] = mon->remote_mps[i]->mpid;
2545     }
2546
2547     ofproto_port_set_cfm(iface->port->bridge->ofproto, iface->ofp_port,
2548                          &cfm, remote_mps, mon->n_remote_mps);
2549     free(remote_mps);
2550 }
2551
2552 /* Read carrier or miimon status directly from 'iface''s netdev, according to
2553  * how 'iface''s port is configured.
2554  *
2555  * Returns true if 'iface' is up, false otherwise. */
2556 static bool
2557 iface_get_carrier(const struct iface *iface)
2558 {
2559     /* XXX */
2560     return netdev_get_carrier(iface->netdev);
2561 }
2562
2563 /* Returns true if 'iface' is synthetic, that is, if we constructed it locally
2564  * instead of obtaining it from the database. */
2565 static bool
2566 iface_is_synthetic(const struct iface *iface)
2567 {
2568     return ovsdb_idl_row_is_synthetic(&iface->cfg->header_);
2569 }
2570 \f
2571 /* Port mirroring. */
2572
2573 static struct mirror *
2574 mirror_find_by_uuid(struct bridge *br, const struct uuid *uuid)
2575 {
2576     struct mirror *m;
2577
2578     HMAP_FOR_EACH_IN_BUCKET (m, hmap_node, uuid_hash(uuid), &br->mirrors) {
2579         if (uuid_equals(uuid, &m->uuid)) {
2580             return m;
2581         }
2582     }
2583     return NULL;
2584 }
2585
2586 static void
2587 bridge_configure_mirrors(struct bridge *br)
2588 {
2589     const struct ovsdb_datum *mc;
2590     unsigned long *flood_vlans;
2591     struct mirror *m, *next;
2592     size_t i;
2593
2594     /* Get rid of deleted mirrors. */
2595     mc = ovsrec_bridge_get_mirrors(br->cfg, OVSDB_TYPE_UUID);
2596     HMAP_FOR_EACH_SAFE (m, next, hmap_node, &br->mirrors) {
2597         union ovsdb_atom atom;
2598
2599         atom.uuid = m->uuid;
2600         if (ovsdb_datum_find_key(mc, &atom, OVSDB_TYPE_UUID) == UINT_MAX) {
2601             mirror_destroy(m);
2602         }
2603     }
2604
2605     /* Add new mirrors and reconfigure existing ones. */
2606     for (i = 0; i < br->cfg->n_mirrors; i++) {
2607         const struct ovsrec_mirror *cfg = br->cfg->mirrors[i];
2608         struct mirror *m = mirror_find_by_uuid(br, &cfg->header_.uuid);
2609         if (!m) {
2610             m = mirror_create(br, cfg);
2611         }
2612         if (!mirror_configure(m, cfg)) {
2613             mirror_destroy(m);
2614         }
2615     }
2616
2617     /* Update flooded vlans (for RSPAN). */
2618     flood_vlans = vlan_bitmap_from_array(br->cfg->flood_vlans,
2619                                          br->cfg->n_flood_vlans);
2620     ofproto_set_flood_vlans(br->ofproto, flood_vlans);
2621     bitmap_free(flood_vlans);
2622 }
2623
2624 static struct mirror *
2625 mirror_create(struct bridge *br, const struct ovsrec_mirror *cfg)
2626 {
2627     struct mirror *m;
2628
2629     m = xzalloc(sizeof *m);
2630     m->uuid = cfg->header_.uuid;
2631     hmap_insert(&br->mirrors, &m->hmap_node, uuid_hash(&m->uuid));
2632     m->bridge = br;
2633     m->name = xstrdup(cfg->name);
2634
2635     return m;
2636 }
2637
2638 static void
2639 mirror_destroy(struct mirror *m)
2640 {
2641     if (m) {
2642         struct bridge *br = m->bridge;
2643
2644         if (br->ofproto) {
2645             ofproto_mirror_unregister(br->ofproto, m);
2646         }
2647
2648         hmap_remove(&br->mirrors, &m->hmap_node);
2649         free(m->name);
2650         free(m);
2651     }
2652 }
2653
2654 static void
2655 mirror_collect_ports(struct mirror *m,
2656                      struct ovsrec_port **in_ports, int n_in_ports,
2657                      void ***out_portsp, size_t *n_out_portsp)
2658 {
2659     void **out_ports = xmalloc(n_in_ports * sizeof *out_ports);
2660     size_t n_out_ports = 0;
2661     size_t i;
2662
2663     for (i = 0; i < n_in_ports; i++) {
2664         const char *name = in_ports[i]->name;
2665         struct port *port = port_lookup(m->bridge, name);
2666         if (port) {
2667             out_ports[n_out_ports++] = port;
2668         } else {
2669             VLOG_WARN("bridge %s: mirror %s cannot match on nonexistent "
2670                       "port %s", m->bridge->name, m->name, name);
2671         }
2672     }
2673     *out_portsp = out_ports;
2674     *n_out_portsp = n_out_ports;
2675 }
2676
2677 static bool
2678 mirror_configure(struct mirror *m, const struct ovsrec_mirror *cfg)
2679 {
2680     struct ofproto_mirror_settings s;
2681     struct port *out_port;
2682     struct port *port;
2683
2684     /* Set name. */
2685     if (strcmp(cfg->name, m->name)) {
2686         free(m->name);
2687         m->name = xstrdup(cfg->name);
2688     }
2689     s.name = m->name;
2690
2691     /* Get output port or VLAN. */
2692     if (cfg->output_port) {
2693         s.out_bundle = port_lookup(m->bridge, cfg->output_port->name);
2694         if (!out_port) {
2695             VLOG_ERR("bridge %s: mirror %s outputs to port not on bridge",
2696                      m->bridge->name, m->name);
2697             return false;
2698         }
2699         s.out_vlan = UINT16_MAX;
2700
2701         if (cfg->output_vlan) {
2702             VLOG_ERR("bridge %s: mirror %s specifies both output port and "
2703                      "output vlan; ignoring output vlan",
2704                      m->bridge->name, m->name);
2705         }
2706     } else if (cfg->output_vlan) {
2707         /* The database should prevent invalid VLAN values. */
2708         s.out_bundle = NULL;
2709         s.out_vlan = *cfg->output_vlan;
2710     } else {
2711         VLOG_ERR("bridge %s: mirror %s does not specify output; ignoring",
2712                  m->bridge->name, m->name);
2713         return false;
2714     }
2715
2716     /* Get port selection. */
2717     if (cfg->select_all) {
2718         size_t n_ports = hmap_count(&m->bridge->ports);
2719         void **ports = xmalloc(n_ports * sizeof *ports);
2720         size_t i;
2721
2722         i = 0;
2723         HMAP_FOR_EACH (port, hmap_node, &m->bridge->ports) {
2724             ports[i++] = port;
2725         }
2726
2727         s.srcs = ports;
2728         s.n_srcs = n_ports;
2729
2730         s.dsts = ports;
2731         s.n_dsts = n_ports;
2732     } else {
2733         /* Get ports, dropping ports that don't exist.
2734          * The IDL ensures that there are no duplicates. */
2735         mirror_collect_ports(m, cfg->select_src_port, cfg->n_select_src_port,
2736                              &s.srcs, &s.n_srcs);
2737         mirror_collect_ports(m, cfg->select_dst_port, cfg->n_select_dst_port,
2738                              &s.dsts, &s.n_dsts);
2739
2740     }
2741
2742     /* Get VLAN selection. */
2743     s.src_vlans = vlan_bitmap_from_array(cfg->select_vlan, cfg->n_select_vlan);
2744
2745     /* Configure. */
2746     ofproto_mirror_register(m->bridge->ofproto, m, &s);
2747
2748     /* Clean up. */
2749     if (s.srcs != s.dsts) {
2750         free(s.dsts);
2751     }
2752     free(s.srcs);
2753     free(s.src_vlans);
2754
2755     return true;
2756 }