bridge: Move packet processing functionality into ofproto.
[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 dp_ifidx_node; /* In struct bridge's "ifaces" hmap. */
93     int dp_ifidx;               /* Index within kernel datapath. */
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 dp_ifidx. */
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_dp_ifidx(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_dp_ifidx(const struct bridge *,
217                                          uint16_t dp_ifidx);
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 dp_ifidx 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_dp_ifidx(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, dp_ifidx_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->dp_ifidx;
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_dp_ifidx(br, ODPP_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_dp_ifidx(struct iface *iface, int dp_ifidx)
814 {
815     struct bridge *br = iface->port->bridge;
816
817     assert(iface->dp_ifidx < 0 && dp_ifidx >= 0);
818     iface->dp_ifidx = dp_ifidx;
819     hmap_insert(&br->ifaces, &iface->dp_ifidx_node, hash_int(dp_ifidx, 0));
820
821 }
822
823 static void
824 bridge_refresh_dp_ifidx(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 "dp_ifidx"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->dp_ifidx = -1;
837         }
838     }
839
840     /* Obtain the correct "dp_ifidx"es from ofproto. */
841     OFPROTO_PORT_FOR_EACH (&ofproto_port, &dump, br->ofproto) {
842         uint32_t odp_port = ofp_port_to_odp_port(ofproto_port.ofp_port);
843         struct iface *iface = iface_lookup(br, ofproto_port.name);
844         if (iface) {
845             if (iface->dp_ifidx >= 0) {
846                 VLOG_WARN("bridge %s: interface %s reported twice",
847                           br->name, ofproto_port.name);
848             } else if (iface_from_dp_ifidx(br, odp_port)) {
849                 VLOG_WARN("bridge %s: interface %"PRIu16" reported twice",
850                           br->name, odp_port);
851             } else {
852                 iface_set_dp_ifidx(iface, odp_port);
853             }
854         }
855     }
856 }
857
858 /* Add a dpif port for any "struct iface" that doesn't have one.
859  * Delete any "struct iface" for which this fails.
860  * Delete any "struct port" that thereby ends up with no ifaces. */
861 static void
862 bridge_add_ofproto_ports(struct bridge *br)
863 {
864     struct port *port, *next_port;
865     struct ofproto_port ofproto_port;
866
867     HMAP_FOR_EACH_SAFE (port, next_port, hmap_node, &br->ports) {
868         struct iface *iface, *next_iface;
869
870         LIST_FOR_EACH_SAFE (iface, next_iface, port_elem, &port->ifaces) {
871             struct shash args;
872             int error;
873
874             /* Open the netdev or reconfigure it. */
875             shash_init(&args);
876             shash_from_ovs_idl_map(iface->cfg->key_options,
877                                    iface->cfg->value_options,
878                                    iface->cfg->n_options, &args);
879             if (!iface->netdev) {
880                 struct netdev_options options;
881                 options.name = iface->name;
882                 options.type = iface->type;
883                 options.args = &args;
884                 options.ethertype = NETDEV_ETH_TYPE_NONE;
885                 error = netdev_open(&options, &iface->netdev);
886             } else {
887                 error = netdev_set_config(iface->netdev, &args);
888             }
889             shash_destroy(&args);
890             if (error) {
891                 VLOG_WARN("could not %s network device %s (%s)",
892                           iface->netdev ? "reconfigure" : "open",
893                           iface->name, strerror(error));
894             }
895
896             /* Add the port, if necessary. */
897             if (iface->netdev && iface->dp_ifidx < 0) {
898                 uint16_t ofp_port;
899                 int error;
900
901                 error = ofproto_port_add(br->ofproto, iface->netdev,
902                                          &ofp_port);
903                 if (!error) {
904                     iface_set_dp_ifidx(iface, ofp_port_to_odp_port(ofp_port));
905                 } else {
906                     netdev_close(iface->netdev);
907                     iface->netdev = NULL;
908                 }
909             }
910
911             /* Delete the iface if  */
912             if (iface->netdev && iface->dp_ifidx >= 0) {
913                 VLOG_DBG("bridge %s: interface %s is on port %d",
914                          br->name, iface->name, iface->dp_ifidx);
915             } else {
916                 if (iface->netdev) {
917                     VLOG_ERR("bridge %s: missing %s interface, dropping",
918                              br->name, iface->name);
919                 } else {
920                     /* We already reported a related error, don't bother
921                      * duplicating it. */
922                 }
923                 iface_set_ofport(iface->cfg, -1);
924                 iface_destroy(iface);
925             }
926         }
927         if (list_is_empty(&port->ifaces)) {
928             VLOG_WARN("%s port has no interfaces, dropping", port->name);
929             port_destroy(port);
930             continue;
931         }
932
933         /* Add bond fake iface if necessary. */
934         if (port_is_bond_fake_iface(port)) {
935             if (ofproto_port_query_by_name(br->ofproto, port->name,
936                                            &ofproto_port)) {
937                 struct netdev_options options;
938                 struct netdev *netdev;
939                 int error;
940
941                 options.name = port->name;
942                 options.type = "internal";
943                 options.args = NULL;
944                 options.ethertype = NETDEV_ETH_TYPE_NONE;
945                 error = netdev_open(&options, &netdev);
946                 if (!error) {
947                     ofproto_port_add(br->ofproto, netdev, NULL);
948                     netdev_close(netdev);
949                 } else {
950                     VLOG_WARN("could not open network device %s (%s)",
951                               port->name, strerror(error));
952                 }
953             } else {
954                 /* Already exists, nothing to do. */
955                 ofproto_port_destroy(&ofproto_port);
956             }
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->dp_ifidx == ODPP_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->dp_ifidx);
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     uint16_t ofp_port = odp_port_to_ofp_port(iface->dp_ifidx);
1284     int old = iface->cfg->lacp_current ? *iface->cfg->lacp_current : -1;
1285     int new = ofproto_port_is_lacp_current(ofproto, ofp_port);
1286
1287     if (old != new) {
1288         bool current = new;
1289         ovsrec_interface_set_lacp_current(iface->cfg, &current, new >= 0);
1290     }
1291     return old != new;
1292 }
1293
1294 static void
1295 iface_refresh_stats(struct iface *iface)
1296 {
1297     struct iface_stat {
1298         char *name;
1299         int offset;
1300     };
1301     static const struct iface_stat iface_stats[] = {
1302         { "rx_packets", offsetof(struct netdev_stats, rx_packets) },
1303         { "tx_packets", offsetof(struct netdev_stats, tx_packets) },
1304         { "rx_bytes", offsetof(struct netdev_stats, rx_bytes) },
1305         { "tx_bytes", offsetof(struct netdev_stats, tx_bytes) },
1306         { "rx_dropped", offsetof(struct netdev_stats, rx_dropped) },
1307         { "tx_dropped", offsetof(struct netdev_stats, tx_dropped) },
1308         { "rx_errors", offsetof(struct netdev_stats, rx_errors) },
1309         { "tx_errors", offsetof(struct netdev_stats, tx_errors) },
1310         { "rx_frame_err", offsetof(struct netdev_stats, rx_frame_errors) },
1311         { "rx_over_err", offsetof(struct netdev_stats, rx_over_errors) },
1312         { "rx_crc_err", offsetof(struct netdev_stats, rx_crc_errors) },
1313         { "collisions", offsetof(struct netdev_stats, collisions) },
1314     };
1315     enum { N_STATS = ARRAY_SIZE(iface_stats) };
1316     const struct iface_stat *s;
1317
1318     char *keys[N_STATS];
1319     int64_t values[N_STATS];
1320     int n;
1321
1322     struct netdev_stats stats;
1323
1324     if (iface_is_synthetic(iface)) {
1325         return;
1326     }
1327
1328     /* Intentionally ignore return value, since errors will set 'stats' to
1329      * all-1s, and we will deal with that correctly below. */
1330     netdev_get_stats(iface->netdev, &stats);
1331
1332     n = 0;
1333     for (s = iface_stats; s < &iface_stats[N_STATS]; s++) {
1334         uint64_t value = *(uint64_t *) (((char *) &stats) + s->offset);
1335         if (value != UINT64_MAX) {
1336             keys[n] = s->name;
1337             values[n] = value;
1338             n++;
1339         }
1340     }
1341
1342     ovsrec_interface_set_statistics(iface->cfg, keys, values, n);
1343 }
1344
1345 static void
1346 refresh_system_stats(const struct ovsrec_open_vswitch *cfg)
1347 {
1348     struct ovsdb_datum datum;
1349     struct shash stats;
1350
1351     shash_init(&stats);
1352     get_system_stats(&stats);
1353
1354     ovsdb_datum_from_shash(&datum, &stats);
1355     ovsdb_idl_txn_write(&cfg->header_, &ovsrec_open_vswitch_col_statistics,
1356                         &datum);
1357 }
1358
1359 static inline const char *
1360 nx_role_to_str(enum nx_role role)
1361 {
1362     switch (role) {
1363     case NX_ROLE_OTHER:
1364         return "other";
1365     case NX_ROLE_MASTER:
1366         return "master";
1367     case NX_ROLE_SLAVE:
1368         return "slave";
1369     default:
1370         return "*** INVALID ROLE ***";
1371     }
1372 }
1373
1374 static void
1375 bridge_refresh_controller_status(const struct bridge *br)
1376 {
1377     struct shash info;
1378     const struct ovsrec_controller *cfg;
1379
1380     ofproto_get_ofproto_controller_info(br->ofproto, &info);
1381
1382     OVSREC_CONTROLLER_FOR_EACH(cfg, idl) {
1383         struct ofproto_controller_info *cinfo =
1384             shash_find_data(&info, cfg->target);
1385
1386         if (cinfo) {
1387             ovsrec_controller_set_is_connected(cfg, cinfo->is_connected);
1388             ovsrec_controller_set_role(cfg, nx_role_to_str(cinfo->role));
1389             ovsrec_controller_set_status(cfg, (char **) cinfo->pairs.keys,
1390                                          (char **) cinfo->pairs.values,
1391                                          cinfo->pairs.n);
1392         } else {
1393             ovsrec_controller_set_is_connected(cfg, false);
1394             ovsrec_controller_set_role(cfg, NULL);
1395             ovsrec_controller_set_status(cfg, NULL, NULL, 0);
1396         }
1397     }
1398
1399     ofproto_free_ofproto_controller_info(&info);
1400 }
1401
1402 void
1403 bridge_run(void)
1404 {
1405     const struct ovsrec_open_vswitch *cfg;
1406
1407     bool datapath_destroyed;
1408     bool database_changed;
1409     struct bridge *br;
1410
1411     /* Let each bridge do the work that it needs to do. */
1412     datapath_destroyed = false;
1413     HMAP_FOR_EACH (br, node, &all_bridges) {
1414         int error = ofproto_run(br->ofproto);
1415         if (error) {
1416             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
1417             VLOG_ERR_RL(&rl, "bridge %s: datapath was destroyed externally, "
1418                         "forcing reconfiguration", br->name);
1419             datapath_destroyed = true;
1420         }
1421     }
1422
1423     /* (Re)configure if necessary. */
1424     database_changed = ovsdb_idl_run(idl);
1425     cfg = ovsrec_open_vswitch_first(idl);
1426 #ifdef HAVE_OPENSSL
1427     /* Re-configure SSL.  We do this on every trip through the main loop,
1428      * instead of just when the database changes, because the contents of the
1429      * key and certificate files can change without the database changing.
1430      *
1431      * We do this before bridge_reconfigure() because that function might
1432      * initiate SSL connections and thus requires SSL to be configured. */
1433     if (cfg && cfg->ssl) {
1434         const struct ovsrec_ssl *ssl = cfg->ssl;
1435
1436         stream_ssl_set_key_and_cert(ssl->private_key, ssl->certificate);
1437         stream_ssl_set_ca_cert_file(ssl->ca_cert, ssl->bootstrap_ca_cert);
1438     }
1439 #endif
1440     if (database_changed || datapath_destroyed) {
1441         if (cfg) {
1442             struct ovsdb_idl_txn *txn = ovsdb_idl_txn_create(idl);
1443
1444             bridge_reconfigure(cfg);
1445
1446             ovsrec_open_vswitch_set_cur_cfg(cfg, cfg->next_cfg);
1447             ovsdb_idl_txn_commit(txn);
1448             ovsdb_idl_txn_destroy(txn); /* XXX */
1449         } else {
1450             /* We still need to reconfigure to avoid dangling pointers to
1451              * now-destroyed ovsrec structures inside bridge data. */
1452             static const struct ovsrec_open_vswitch null_cfg;
1453
1454             bridge_reconfigure(&null_cfg);
1455         }
1456     }
1457
1458     /* Refresh system and interface stats if necessary. */
1459     if (time_msec() >= stats_timer) {
1460         if (cfg) {
1461             struct ovsdb_idl_txn *txn;
1462
1463             txn = ovsdb_idl_txn_create(idl);
1464             HMAP_FOR_EACH (br, node, &all_bridges) {
1465                 struct port *port;
1466
1467                 HMAP_FOR_EACH (port, hmap_node, &br->ports) {
1468                     struct iface *iface;
1469
1470                     LIST_FOR_EACH (iface, port_elem, &port->ifaces) {
1471                         iface_refresh_stats(iface);
1472                         iface_refresh_status(iface);
1473                     }
1474                 }
1475                 bridge_refresh_controller_status(br);
1476             }
1477             refresh_system_stats(cfg);
1478             ovsdb_idl_txn_commit(txn);
1479             ovsdb_idl_txn_destroy(txn); /* XXX */
1480         }
1481
1482         stats_timer = time_msec() + STATS_INTERVAL;
1483     }
1484
1485     if (time_msec() >= db_limiter) {
1486         struct ovsdb_idl_txn *txn;
1487         bool changed = false;
1488
1489         txn = ovsdb_idl_txn_create(idl);
1490         HMAP_FOR_EACH (br, node, &all_bridges) {
1491             struct port *port;
1492
1493             HMAP_FOR_EACH (port, hmap_node, &br->ports) {
1494                 struct iface *iface;
1495
1496                 LIST_FOR_EACH (iface, port_elem, &port->ifaces) {
1497                     changed = iface_refresh_cfm_stats(iface) || changed;
1498                     changed = iface_refresh_lacp_stats(iface) || changed;
1499                 }
1500             }
1501         }
1502
1503         if (changed) {
1504             db_limiter = time_msec() + DB_LIMIT_INTERVAL;
1505         }
1506
1507         ovsdb_idl_txn_commit(txn);
1508         ovsdb_idl_txn_destroy(txn);
1509     }
1510 }
1511
1512 void
1513 bridge_wait(void)
1514 {
1515     struct bridge *br;
1516
1517     HMAP_FOR_EACH (br, node, &all_bridges) {
1518         ofproto_wait(br->ofproto);
1519     }
1520     ovsdb_idl_wait(idl);
1521     poll_timer_wait_until(stats_timer);
1522
1523     if (db_limiter > time_msec()) {
1524         poll_timer_wait_until(db_limiter);
1525     }
1526 }
1527 \f
1528 /* CFM unixctl user interface functions. */
1529 static void
1530 cfm_unixctl_show(struct unixctl_conn *conn,
1531                  const char *args, void *aux OVS_UNUSED)
1532 {
1533     struct ds ds = DS_EMPTY_INITIALIZER;
1534     struct iface *iface;
1535     const struct cfm *cfm;
1536
1537     iface = iface_find(args);
1538     if (!iface) {
1539         unixctl_command_reply(conn, 501, "no such interface");
1540         return;
1541     }
1542
1543     cfm = ofproto_port_get_cfm(iface->port->bridge->ofproto, iface->dp_ifidx);
1544
1545     if (!cfm) {
1546         unixctl_command_reply(conn, 501, "CFM not enabled");
1547         return;
1548     }
1549
1550     cfm_dump_ds(cfm, &ds);
1551     unixctl_command_reply(conn, 200, ds_cstr(&ds));
1552     ds_destroy(&ds);
1553 }
1554 \f
1555 /* QoS unixctl user interface functions. */
1556
1557 struct qos_unixctl_show_cbdata {
1558     struct ds *ds;
1559     struct iface *iface;
1560 };
1561
1562 static void
1563 qos_unixctl_show_cb(unsigned int queue_id,
1564                     const struct shash *details,
1565                     void *aux)
1566 {
1567     struct qos_unixctl_show_cbdata *data = aux;
1568     struct ds *ds = data->ds;
1569     struct iface *iface = data->iface;
1570     struct netdev_queue_stats stats;
1571     struct shash_node *node;
1572     int error;
1573
1574     ds_put_cstr(ds, "\n");
1575     if (queue_id) {
1576         ds_put_format(ds, "Queue %u:\n", queue_id);
1577     } else {
1578         ds_put_cstr(ds, "Default:\n");
1579     }
1580
1581     SHASH_FOR_EACH (node, details) {
1582         ds_put_format(ds, "\t%s: %s\n", node->name, (char *)node->data);
1583     }
1584
1585     error = netdev_get_queue_stats(iface->netdev, queue_id, &stats);
1586     if (!error) {
1587         if (stats.tx_packets != UINT64_MAX) {
1588             ds_put_format(ds, "\ttx_packets: %"PRIu64"\n", stats.tx_packets);
1589         }
1590
1591         if (stats.tx_bytes != UINT64_MAX) {
1592             ds_put_format(ds, "\ttx_bytes: %"PRIu64"\n", stats.tx_bytes);
1593         }
1594
1595         if (stats.tx_errors != UINT64_MAX) {
1596             ds_put_format(ds, "\ttx_errors: %"PRIu64"\n", stats.tx_errors);
1597         }
1598     } else {
1599         ds_put_format(ds, "\tFailed to get statistics for queue %u: %s",
1600                       queue_id, strerror(error));
1601     }
1602 }
1603
1604 static void
1605 qos_unixctl_show(struct unixctl_conn *conn,
1606                  const char *args, void *aux OVS_UNUSED)
1607 {
1608     struct ds ds = DS_EMPTY_INITIALIZER;
1609     struct shash sh = SHASH_INITIALIZER(&sh);
1610     struct iface *iface;
1611     const char *type;
1612     struct shash_node *node;
1613     struct qos_unixctl_show_cbdata data;
1614     int error;
1615
1616     iface = iface_find(args);
1617     if (!iface) {
1618         unixctl_command_reply(conn, 501, "no such interface");
1619         return;
1620     }
1621
1622     netdev_get_qos(iface->netdev, &type, &sh);
1623
1624     if (*type != '\0') {
1625         ds_put_format(&ds, "QoS: %s %s\n", iface->name, type);
1626
1627         SHASH_FOR_EACH (node, &sh) {
1628             ds_put_format(&ds, "%s: %s\n", node->name, (char *)node->data);
1629         }
1630
1631         data.ds = &ds;
1632         data.iface = iface;
1633         error = netdev_dump_queues(iface->netdev, qos_unixctl_show_cb, &data);
1634
1635         if (error) {
1636             ds_put_format(&ds, "failed to dump queues: %s", strerror(error));
1637         }
1638         unixctl_command_reply(conn, 200, ds_cstr(&ds));
1639     } else {
1640         ds_put_format(&ds, "QoS not configured on %s\n", iface->name);
1641         unixctl_command_reply(conn, 501, ds_cstr(&ds));
1642     }
1643
1644     shash_destroy_free_data(&sh);
1645     ds_destroy(&ds);
1646 }
1647 \f
1648 /* Bridge reconfiguration functions. */
1649 static void
1650 bridge_create(const struct ovsrec_bridge *br_cfg)
1651 {
1652     struct bridge *br;
1653
1654     assert(!bridge_lookup(br_cfg->name));
1655     br = xzalloc(sizeof *br);
1656
1657     br->name = xstrdup(br_cfg->name);
1658     br->type = xstrdup(dpif_normalize_type(br_cfg->datapath_type));
1659     br->cfg = br_cfg;
1660     eth_addr_nicira_random(br->default_ea);
1661
1662     hmap_init(&br->ports);
1663     hmap_init(&br->ifaces);
1664     hmap_init(&br->iface_by_name);
1665     hmap_init(&br->mirrors);
1666
1667     hmap_insert(&all_bridges, &br->node, hash_string(br->name, 0));
1668 }
1669
1670 static void
1671 bridge_destroy(struct bridge *br)
1672 {
1673     if (br) {
1674         struct mirror *mirror, *next_mirror;
1675         struct port *port, *next_port;
1676
1677         HMAP_FOR_EACH_SAFE (port, next_port, hmap_node, &br->ports) {
1678             port_destroy(port);
1679         }
1680         HMAP_FOR_EACH_SAFE (mirror, next_mirror, hmap_node, &br->mirrors) {
1681             mirror_destroy(mirror);
1682         }
1683         hmap_remove(&all_bridges, &br->node);
1684         ofproto_destroy(br->ofproto);
1685         hmap_destroy(&br->ifaces);
1686         hmap_destroy(&br->ports);
1687         hmap_destroy(&br->iface_by_name);
1688         hmap_destroy(&br->mirrors);
1689         free(br->name);
1690         free(br->type);
1691         free(br);
1692     }
1693 }
1694
1695 static struct bridge *
1696 bridge_lookup(const char *name)
1697 {
1698     struct bridge *br;
1699
1700     HMAP_FOR_EACH_WITH_HASH (br, node, hash_string(name, 0), &all_bridges) {
1701         if (!strcmp(br->name, name)) {
1702             return br;
1703         }
1704     }
1705     return NULL;
1706 }
1707
1708 /* Handle requests for a listing of all flows known by the OpenFlow
1709  * stack, including those normally hidden. */
1710 static void
1711 bridge_unixctl_dump_flows(struct unixctl_conn *conn,
1712                           const char *args, void *aux OVS_UNUSED)
1713 {
1714     struct bridge *br;
1715     struct ds results;
1716
1717     br = bridge_lookup(args);
1718     if (!br) {
1719         unixctl_command_reply(conn, 501, "Unknown bridge");
1720         return;
1721     }
1722
1723     ds_init(&results);
1724     ofproto_get_all_flows(br->ofproto, &results);
1725
1726     unixctl_command_reply(conn, 200, ds_cstr(&results));
1727     ds_destroy(&results);
1728 }
1729
1730 /* "bridge/reconnect [BRIDGE]": makes BRIDGE drop all of its controller
1731  * connections and reconnect.  If BRIDGE is not specified, then all bridges
1732  * drop their controller connections and reconnect. */
1733 static void
1734 bridge_unixctl_reconnect(struct unixctl_conn *conn,
1735                          const char *args, void *aux OVS_UNUSED)
1736 {
1737     struct bridge *br;
1738     if (args[0] != '\0') {
1739         br = bridge_lookup(args);
1740         if (!br) {
1741             unixctl_command_reply(conn, 501, "Unknown bridge");
1742             return;
1743         }
1744         ofproto_reconnect_controllers(br->ofproto);
1745     } else {
1746         HMAP_FOR_EACH (br, node, &all_bridges) {
1747             ofproto_reconnect_controllers(br->ofproto);
1748         }
1749     }
1750     unixctl_command_reply(conn, 200, NULL);
1751 }
1752
1753 static size_t
1754 bridge_get_controllers(const struct bridge *br,
1755                        struct ovsrec_controller ***controllersp)
1756 {
1757     struct ovsrec_controller **controllers;
1758     size_t n_controllers;
1759
1760     controllers = br->cfg->controller;
1761     n_controllers = br->cfg->n_controller;
1762
1763     if (n_controllers == 1 && !strcmp(controllers[0]->target, "none")) {
1764         controllers = NULL;
1765         n_controllers = 0;
1766     }
1767
1768     if (controllersp) {
1769         *controllersp = controllers;
1770     }
1771     return n_controllers;
1772 }
1773
1774 /* Adds and deletes "struct port"s and "struct iface"s under 'br' to match
1775  * those configured in 'br->cfg'. */
1776 static void
1777 bridge_add_del_ports(struct bridge *br)
1778 {
1779     struct port *port, *next;
1780     struct shash_node *node;
1781     struct shash new_ports;
1782     size_t i;
1783
1784     /* Collect new ports. */
1785     shash_init(&new_ports);
1786     for (i = 0; i < br->cfg->n_ports; i++) {
1787         const char *name = br->cfg->ports[i]->name;
1788         if (!shash_add_once(&new_ports, name, br->cfg->ports[i])) {
1789             VLOG_WARN("bridge %s: %s specified twice as bridge port",
1790                       br->name, name);
1791         }
1792     }
1793     if (bridge_get_controllers(br, NULL)
1794         && !shash_find(&new_ports, br->name)) {
1795         VLOG_WARN("bridge %s: no port named %s, synthesizing one",
1796                   br->name, br->name);
1797
1798         br->synth_local_port.interfaces = &br->synth_local_ifacep;
1799         br->synth_local_port.n_interfaces = 1;
1800         br->synth_local_port.name = br->name;
1801
1802         br->synth_local_iface.name = br->name;
1803         br->synth_local_iface.type = "internal";
1804
1805         br->synth_local_ifacep = &br->synth_local_iface;
1806
1807         shash_add(&new_ports, br->name, &br->synth_local_port);
1808     }
1809
1810     /* Get rid of deleted ports.
1811      * Get rid of deleted interfaces on ports that still exist.
1812      * Update 'cfg' of ports that still exist. */
1813     HMAP_FOR_EACH_SAFE (port, next, hmap_node, &br->ports) {
1814         port->cfg = shash_find_data(&new_ports, port->name);
1815         if (!port->cfg) {
1816             port_destroy(port);
1817         } else {
1818             port_del_ifaces(port);
1819         }
1820     }
1821
1822     /* Create new ports.
1823      * Add new interfaces to existing ports. */
1824     SHASH_FOR_EACH (node, &new_ports) {
1825         struct port *port = port_lookup(br, node->name);
1826         if (!port) {
1827             struct ovsrec_port *cfg = node->data;
1828             port = port_create(br, cfg);
1829         }
1830         port_add_ifaces(port);
1831         if (list_is_empty(&port->ifaces)) {
1832             VLOG_WARN("bridge %s: port %s has no interfaces, dropping",
1833                       br->name, port->name);
1834             port_destroy(port);
1835         }
1836     }
1837     shash_destroy(&new_ports);
1838 }
1839
1840 /* Initializes 'oc' appropriately as a management service controller for
1841  * 'br'.
1842  *
1843  * The caller must free oc->target when it is no longer needed. */
1844 static void
1845 bridge_ofproto_controller_for_mgmt(const struct bridge *br,
1846                                    struct ofproto_controller *oc)
1847 {
1848     oc->target = xasprintf("punix:%s/%s.mgmt", ovs_rundir(), br->name);
1849     oc->max_backoff = 0;
1850     oc->probe_interval = 60;
1851     oc->band = OFPROTO_OUT_OF_BAND;
1852     oc->rate_limit = 0;
1853     oc->burst_limit = 0;
1854 }
1855
1856 /* Converts ovsrec_controller 'c' into an ofproto_controller in 'oc'.  */
1857 static void
1858 bridge_ofproto_controller_from_ovsrec(const struct ovsrec_controller *c,
1859                                       struct ofproto_controller *oc)
1860 {
1861     oc->target = c->target;
1862     oc->max_backoff = c->max_backoff ? *c->max_backoff / 1000 : 8;
1863     oc->probe_interval = c->inactivity_probe ? *c->inactivity_probe / 1000 : 5;
1864     oc->band = (!c->connection_mode || !strcmp(c->connection_mode, "in-band")
1865                 ? OFPROTO_IN_BAND : OFPROTO_OUT_OF_BAND);
1866     oc->rate_limit = c->controller_rate_limit ? *c->controller_rate_limit : 0;
1867     oc->burst_limit = (c->controller_burst_limit
1868                        ? *c->controller_burst_limit : 0);
1869 }
1870
1871 /* Configures the IP stack for 'br''s local interface properly according to the
1872  * configuration in 'c'.  */
1873 static void
1874 bridge_configure_local_iface_netdev(struct bridge *br,
1875                                     struct ovsrec_controller *c)
1876 {
1877     struct netdev *netdev;
1878     struct in_addr mask, gateway;
1879
1880     struct iface *local_iface;
1881     struct in_addr ip;
1882
1883     /* If there's no local interface or no IP address, give up. */
1884     local_iface = iface_from_dp_ifidx(br, ODPP_LOCAL);
1885     if (!local_iface || !c->local_ip || !inet_aton(c->local_ip, &ip)) {
1886         return;
1887     }
1888
1889     /* Bring up the local interface. */
1890     netdev = local_iface->netdev;
1891     netdev_turn_flags_on(netdev, NETDEV_UP, true);
1892
1893     /* Configure the IP address and netmask. */
1894     if (!c->local_netmask
1895         || !inet_aton(c->local_netmask, &mask)
1896         || !mask.s_addr) {
1897         mask.s_addr = guess_netmask(ip.s_addr);
1898     }
1899     if (!netdev_set_in4(netdev, ip, mask)) {
1900         VLOG_INFO("bridge %s: configured IP address "IP_FMT", netmask "IP_FMT,
1901                   br->name, IP_ARGS(&ip.s_addr), IP_ARGS(&mask.s_addr));
1902     }
1903
1904     /* Configure the default gateway. */
1905     if (c->local_gateway
1906         && inet_aton(c->local_gateway, &gateway)
1907         && gateway.s_addr) {
1908         if (!netdev_add_router(netdev, gateway)) {
1909             VLOG_INFO("bridge %s: configured gateway "IP_FMT,
1910                       br->name, IP_ARGS(&gateway.s_addr));
1911         }
1912     }
1913 }
1914
1915 static void
1916 bridge_configure_remotes(struct bridge *br,
1917                          const struct sockaddr_in *managers, size_t n_managers)
1918 {
1919     const char *disable_ib_str, *queue_id_str;
1920     bool disable_in_band = false;
1921     int queue_id;
1922
1923     struct ovsrec_controller **controllers;
1924     size_t n_controllers;
1925
1926     enum ofproto_fail_mode fail_mode;
1927
1928     struct ofproto_controller *ocs;
1929     size_t n_ocs;
1930     size_t i;
1931
1932     /* Check if we should disable in-band control on this bridge. */
1933     disable_ib_str = bridge_get_other_config(br->cfg, "disable-in-band");
1934     if (disable_ib_str && !strcmp(disable_ib_str, "true")) {
1935         disable_in_band = true;
1936     }
1937
1938     /* Set OpenFlow queue ID for in-band control. */
1939     queue_id_str = bridge_get_other_config(br->cfg, "in-band-queue");
1940     queue_id = queue_id_str ? strtol(queue_id_str, NULL, 10) : -1;
1941     ofproto_set_in_band_queue(br->ofproto, queue_id);
1942
1943     if (disable_in_band) {
1944         ofproto_set_extra_in_band_remotes(br->ofproto, NULL, 0);
1945     } else {
1946         ofproto_set_extra_in_band_remotes(br->ofproto, managers, n_managers);
1947     }
1948
1949     n_controllers = bridge_get_controllers(br, &controllers);
1950
1951     ocs = xmalloc((n_controllers + 1) * sizeof *ocs);
1952     n_ocs = 0;
1953
1954     bridge_ofproto_controller_for_mgmt(br, &ocs[n_ocs++]);
1955     for (i = 0; i < n_controllers; i++) {
1956         struct ovsrec_controller *c = controllers[i];
1957
1958         if (!strncmp(c->target, "punix:", 6)
1959             || !strncmp(c->target, "unix:", 5)) {
1960             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
1961
1962             /* Prevent remote ovsdb-server users from accessing arbitrary Unix
1963              * domain sockets and overwriting arbitrary local files. */
1964             VLOG_ERR_RL(&rl, "bridge %s: not adding Unix domain socket "
1965                         "controller \"%s\" due to possibility for remote "
1966                         "exploit", br->name, c->target);
1967             continue;
1968         }
1969
1970         bridge_configure_local_iface_netdev(br, c);
1971         bridge_ofproto_controller_from_ovsrec(c, &ocs[n_ocs]);
1972         if (disable_in_band) {
1973             ocs[n_ocs].band = OFPROTO_OUT_OF_BAND;
1974         }
1975         n_ocs++;
1976     }
1977
1978     ofproto_set_controllers(br->ofproto, ocs, n_ocs);
1979     free(ocs[0].target); /* From bridge_ofproto_controller_for_mgmt(). */
1980     free(ocs);
1981
1982     /* Set the fail-mode. */
1983     fail_mode = !br->cfg->fail_mode
1984                 || !strcmp(br->cfg->fail_mode, "standalone")
1985                     ? OFPROTO_FAIL_STANDALONE
1986                     : OFPROTO_FAIL_SECURE;
1987     ofproto_set_fail_mode(br->ofproto, fail_mode);
1988
1989     /* Configure OpenFlow controller connection snooping. */
1990     if (!ofproto_has_snoops(br->ofproto)) {
1991         struct sset snoops;
1992
1993         sset_init(&snoops);
1994         sset_add_and_free(&snoops, xasprintf("punix:%s/%s.snoop",
1995                                              ovs_rundir(), br->name));
1996         ofproto_set_snoops(br->ofproto, &snoops);
1997         sset_destroy(&snoops);
1998     }
1999 }
2000 \f
2001 /* Port functions. */
2002
2003 static struct port *
2004 port_create(struct bridge *br, const struct ovsrec_port *cfg)
2005 {
2006     struct port *port;
2007
2008     port = xzalloc(sizeof *port);
2009     port->bridge = br;
2010     port->name = xstrdup(cfg->name);
2011     port->cfg = cfg;
2012     list_init(&port->ifaces);
2013
2014     hmap_insert(&br->ports, &port->hmap_node, hash_string(port->name, 0));
2015
2016     VLOG_INFO("created port %s on bridge %s", port->name, br->name);
2017
2018     return port;
2019 }
2020
2021 static const char *
2022 get_port_other_config(const struct ovsrec_port *port, const char *key,
2023                       const char *default_value)
2024 {
2025     const char *value;
2026
2027     value = get_ovsrec_key_value(&port->header_, &ovsrec_port_col_other_config,
2028                                  key);
2029     return value ? value : default_value;
2030 }
2031
2032 static const char *
2033 get_interface_other_config(const struct ovsrec_interface *iface,
2034                            const char *key, const char *default_value)
2035 {
2036     const char *value;
2037
2038     value = get_ovsrec_key_value(&iface->header_,
2039                                  &ovsrec_interface_col_other_config, key);
2040     return value ? value : default_value;
2041 }
2042
2043 /* Deletes interfaces from 'port' that are no longer configured for it. */
2044 static void
2045 port_del_ifaces(struct port *port)
2046 {
2047     struct iface *iface, *next;
2048     struct sset new_ifaces;
2049     size_t i;
2050
2051     /* Collect list of new interfaces. */
2052     sset_init(&new_ifaces);
2053     for (i = 0; i < port->cfg->n_interfaces; i++) {
2054         const char *name = port->cfg->interfaces[i]->name;
2055         sset_add(&new_ifaces, name);
2056     }
2057
2058     /* Get rid of deleted interfaces. */
2059     LIST_FOR_EACH_SAFE (iface, next, port_elem, &port->ifaces) {
2060         if (!sset_contains(&new_ifaces, iface->name)) {
2061             iface_destroy(iface);
2062         }
2063     }
2064
2065     sset_destroy(&new_ifaces);
2066 }
2067
2068 /* Adds new interfaces to 'port' and updates 'type' and 'cfg' members of
2069  * existing ones. */
2070 static void
2071 port_add_ifaces(struct port *port)
2072 {
2073     struct shash new_ifaces;
2074     struct shash_node *node;
2075     size_t i;
2076
2077     /* Collect new ifaces. */
2078     shash_init(&new_ifaces);
2079     for (i = 0; i < port->cfg->n_interfaces; i++) {
2080         const struct ovsrec_interface *cfg = port->cfg->interfaces[i];
2081         if (!shash_add_once(&new_ifaces, cfg->name, cfg)) {
2082             VLOG_WARN("port %s: %s specified twice as port interface",
2083                       port->name, cfg->name);
2084             iface_set_ofport(cfg, -1);
2085         }
2086     }
2087
2088     /* Create new interfaces.
2089      * Update interface types and 'cfg' members. */
2090     SHASH_FOR_EACH (node, &new_ifaces) {
2091         const struct ovsrec_interface *cfg = node->data;
2092         const char *iface_name = node->name;
2093         struct iface *iface;
2094
2095         iface = iface_lookup(port->bridge, iface_name);
2096         if (!iface) {
2097             iface = iface_create(port, cfg);
2098         } else {
2099             iface->cfg = cfg;
2100         }
2101
2102         /* Determine interface type.  The local port always has type
2103          * "internal".  Other ports take their type from the database and
2104          * default to "system" if none is specified. */
2105         iface->type = (!strcmp(iface_name, port->bridge->name) ? "internal"
2106                        : cfg->type[0] ? cfg->type
2107                        : "system");
2108     }
2109     shash_destroy(&new_ifaces);
2110 }
2111
2112 static void
2113 port_destroy(struct port *port)
2114 {
2115     if (port) {
2116         struct bridge *br = port->bridge;
2117         struct iface *iface, *next;
2118
2119         if (br->ofproto) {
2120             ofproto_bundle_unregister(br->ofproto, port);
2121         }
2122
2123         LIST_FOR_EACH_SAFE (iface, next, port_elem, &port->ifaces) {
2124             iface_destroy(iface);
2125         }
2126
2127         hmap_remove(&br->ports, &port->hmap_node);
2128
2129         VLOG_INFO("destroyed port %s on bridge %s", port->name, br->name);
2130
2131         free(port->name);
2132         free(port);
2133     }
2134 }
2135
2136 static struct port *
2137 port_lookup(const struct bridge *br, const char *name)
2138 {
2139     struct port *port;
2140
2141     HMAP_FOR_EACH_WITH_HASH (port, hmap_node, hash_string(name, 0),
2142                              &br->ports) {
2143         if (!strcmp(port->name, name)) {
2144             return port;
2145         }
2146     }
2147     return NULL;
2148 }
2149
2150 static bool
2151 enable_lacp(struct port *port, bool *activep)
2152 {
2153     if (!port->cfg->lacp) {
2154         /* XXX when LACP implementation has been sufficiently tested, enable by
2155          * default and make active on bonded ports. */
2156         return false;
2157     } else if (!strcmp(port->cfg->lacp, "off")) {
2158         return false;
2159     } else if (!strcmp(port->cfg->lacp, "active")) {
2160         *activep = true;
2161         return true;
2162     } else if (!strcmp(port->cfg->lacp, "passive")) {
2163         *activep = false;
2164         return true;
2165     } else {
2166         VLOG_WARN("port %s: unknown LACP mode %s",
2167                   port->name, port->cfg->lacp);
2168         return false;
2169     }
2170 }
2171
2172 static struct lacp_settings *
2173 port_configure_lacp(struct port *port, struct lacp_settings *s)
2174 {
2175     const char *lacp_time;
2176     long long int custom_time;
2177     int priority;
2178
2179     if (!enable_lacp(port, &s->active)) {
2180         return NULL;
2181     }
2182
2183     s->name = port->name;
2184     memcpy(s->id, port->bridge->ea, ETH_ADDR_LEN);
2185
2186     /* Prefer bondable links if unspecified. */
2187     priority = atoi(get_port_other_config(port->cfg, "lacp-system-priority",
2188                                           "0"));
2189     s->priority = (priority > 0 && priority <= UINT16_MAX
2190                    ? priority
2191                    : UINT16_MAX - !list_is_short(&port->ifaces));
2192
2193     s->strict = !strcmp(get_port_other_config(port->cfg, "lacp-strict",
2194                                               "false"),
2195                         "true");
2196
2197     lacp_time = get_port_other_config(port->cfg, "lacp-time", "slow");
2198     custom_time = atoi(lacp_time);
2199     if (!strcmp(lacp_time, "fast")) {
2200         s->lacp_time = LACP_TIME_FAST;
2201     } else if (!strcmp(lacp_time, "slow")) {
2202         s->lacp_time = LACP_TIME_SLOW;
2203     } else if (custom_time > 0) {
2204         s->lacp_time = LACP_TIME_CUSTOM;
2205         s->custom_time = custom_time;
2206     } else {
2207         s->lacp_time = LACP_TIME_SLOW;
2208     }
2209
2210     return s;
2211 }
2212
2213 static void
2214 iface_configure_lacp(struct iface *iface, struct lacp_slave_settings *s)
2215 {
2216     int priority, portid;
2217
2218     portid = atoi(get_interface_other_config(iface->cfg, "lacp-port-id", "0"));
2219     priority = atoi(get_interface_other_config(iface->cfg,
2220                                                "lacp-port-priority", "0"));
2221
2222     if (portid <= 0 || portid > UINT16_MAX) {
2223         portid = iface->dp_ifidx;
2224     }
2225
2226     if (priority <= 0 || priority > UINT16_MAX) {
2227         priority = UINT16_MAX;
2228     }
2229
2230     s->name = iface->name;
2231     s->id = iface->dp_ifidx;
2232     s->id = portid;
2233     s->priority = priority;
2234 }
2235
2236 static void
2237 port_configure_bond(struct port *port, struct bond_settings *s)
2238 {
2239     const char *detect_s;
2240
2241     s->name = port->name;
2242     s->balance = BM_SLB;
2243     if (port->cfg->bond_mode
2244         && !bond_mode_from_string(&s->balance, port->cfg->bond_mode)) {
2245         VLOG_WARN("port %s: unknown bond_mode %s, defaulting to %s",
2246                   port->name, port->cfg->bond_mode,
2247                   bond_mode_to_string(s->balance));
2248     }
2249
2250     s->detect = BLSM_CARRIER;
2251     detect_s = get_port_other_config(port->cfg, "bond-detect-mode", NULL);
2252     if (detect_s && !bond_detect_mode_from_string(&s->detect, detect_s)) {
2253         VLOG_WARN("port %s: unsupported bond-detect-mode %s, "
2254                   "defaulting to %s",
2255                   port->name, detect_s, bond_detect_mode_to_string(s->detect));
2256     }
2257
2258     s->miimon_interval = atoi(
2259         get_port_other_config(port->cfg, "bond-miimon-interval", "200"));
2260     if (s->miimon_interval < 100) {
2261         s->miimon_interval = 100;
2262     }
2263
2264     s->up_delay = MAX(0, port->cfg->bond_updelay);
2265     s->down_delay = MAX(0, port->cfg->bond_downdelay);
2266     s->rebalance_interval = atoi(
2267         get_port_other_config(port->cfg, "bond-rebalance-interval", "10000"));
2268     if (s->rebalance_interval < 1000) {
2269         s->rebalance_interval = 1000;
2270     }
2271
2272     s->fake_iface = port->cfg->bond_fake_iface;
2273 }
2274 \f
2275 /* Interface functions. */
2276
2277 static struct iface *
2278 iface_create(struct port *port, const struct ovsrec_interface *if_cfg)
2279 {
2280     struct bridge *br = port->bridge;
2281     struct iface *iface;
2282     char *name = if_cfg->name;
2283
2284     iface = xzalloc(sizeof *iface);
2285     iface->port = port;
2286     iface->name = xstrdup(name);
2287     iface->dp_ifidx = -1;
2288     iface->tag = tag_create_random();
2289     iface->netdev = NULL;
2290     iface->cfg = if_cfg;
2291
2292     hmap_insert(&br->iface_by_name, &iface->name_node, hash_string(name, 0));
2293
2294     list_push_back(&port->ifaces, &iface->port_elem);
2295
2296     VLOG_DBG("attached network device %s to port %s", iface->name, port->name);
2297
2298     return iface;
2299 }
2300
2301 static void
2302 iface_destroy(struct iface *iface)
2303 {
2304     if (iface) {
2305         struct port *port = iface->port;
2306         struct bridge *br = port->bridge;
2307
2308         if (br->ofproto && iface->dp_ifidx >= 0) {
2309             ofproto_port_unregister(br->ofproto, iface->dp_ifidx);
2310         }
2311
2312         if (iface->dp_ifidx >= 0) {
2313             hmap_remove(&br->ifaces, &iface->dp_ifidx_node);
2314         }
2315
2316         list_remove(&iface->port_elem);
2317         hmap_remove(&br->iface_by_name, &iface->name_node);
2318
2319         netdev_close(iface->netdev);
2320
2321         free(iface->name);
2322         free(iface);
2323     }
2324 }
2325
2326 static struct iface *
2327 iface_lookup(const struct bridge *br, const char *name)
2328 {
2329     struct iface *iface;
2330
2331     HMAP_FOR_EACH_WITH_HASH (iface, name_node, hash_string(name, 0),
2332                              &br->iface_by_name) {
2333         if (!strcmp(iface->name, name)) {
2334             return iface;
2335         }
2336     }
2337
2338     return NULL;
2339 }
2340
2341 static struct iface *
2342 iface_find(const char *name)
2343 {
2344     const struct bridge *br;
2345
2346     HMAP_FOR_EACH (br, node, &all_bridges) {
2347         struct iface *iface = iface_lookup(br, name);
2348
2349         if (iface) {
2350             return iface;
2351         }
2352     }
2353     return NULL;
2354 }
2355
2356 static struct iface *
2357 iface_from_dp_ifidx(const struct bridge *br, uint16_t dp_ifidx)
2358 {
2359     struct iface *iface;
2360
2361     HMAP_FOR_EACH_IN_BUCKET (iface, dp_ifidx_node,
2362                              hash_int(dp_ifidx, 0), &br->ifaces) {
2363         if (iface->dp_ifidx == dp_ifidx) {
2364             return iface;
2365         }
2366     }
2367     return NULL;
2368 }
2369
2370 /* Set Ethernet address of 'iface', if one is specified in the configuration
2371  * file. */
2372 static void
2373 iface_set_mac(struct iface *iface)
2374 {
2375     uint8_t ea[ETH_ADDR_LEN];
2376
2377     if (!strcmp(iface->type, "internal")
2378         && iface->cfg->mac && eth_addr_from_string(iface->cfg->mac, ea)) {
2379         if (iface->dp_ifidx == ODPP_LOCAL) {
2380             VLOG_ERR("interface %s: ignoring mac in Interface record "
2381                      "(use Bridge record to set local port's mac)",
2382                      iface->name);
2383         } else if (eth_addr_is_multicast(ea)) {
2384             VLOG_ERR("interface %s: cannot set MAC to multicast address",
2385                      iface->name);
2386         } else {
2387             int error = netdev_set_etheraddr(iface->netdev, ea);
2388             if (error) {
2389                 VLOG_ERR("interface %s: setting MAC failed (%s)",
2390                          iface->name, strerror(error));
2391             }
2392         }
2393     }
2394 }
2395
2396 /* Sets the ofport column of 'if_cfg' to 'ofport'. */
2397 static void
2398 iface_set_ofport(const struct ovsrec_interface *if_cfg, int64_t ofport)
2399 {
2400     if (if_cfg && !ovsdb_idl_row_is_synthetic(&if_cfg->header_)) {
2401         ovsrec_interface_set_ofport(if_cfg, &ofport, 1);
2402     }
2403 }
2404
2405 /* Adds the 'n' key-value pairs in 'keys' in 'values' to 'shash'.
2406  *
2407  * The value strings in '*shash' are taken directly from values[], not copied,
2408  * so the caller should not modify or free them. */
2409 static void
2410 shash_from_ovs_idl_map(char **keys, char **values, size_t n,
2411                        struct shash *shash)
2412 {
2413     size_t i;
2414
2415     shash_init(shash);
2416     for (i = 0; i < n; i++) {
2417         shash_add(shash, keys[i], values[i]);
2418     }
2419 }
2420
2421 /* Creates 'keys' and 'values' arrays from 'shash'.
2422  *
2423  * Sets 'keys' and 'values' to heap allocated arrays representing the key-value
2424  * pairs in 'shash'.  The caller takes ownership of 'keys' and 'values'.  They
2425  * are populated with with strings taken directly from 'shash' and thus have
2426  * the same ownership of the key-value pairs in shash.
2427  */
2428 static void
2429 shash_to_ovs_idl_map(struct shash *shash,
2430                      char ***keys, char ***values, size_t *n)
2431 {
2432     size_t i, count;
2433     char **k, **v;
2434     struct shash_node *sn;
2435
2436     count = shash_count(shash);
2437
2438     k = xmalloc(count * sizeof *k);
2439     v = xmalloc(count * sizeof *v);
2440
2441     i = 0;
2442     SHASH_FOR_EACH(sn, shash) {
2443         k[i] = sn->name;
2444         v[i] = sn->data;
2445         i++;
2446     }
2447
2448     *n      = count;
2449     *keys   = k;
2450     *values = v;
2451 }
2452
2453 struct iface_delete_queues_cbdata {
2454     struct netdev *netdev;
2455     const struct ovsdb_datum *queues;
2456 };
2457
2458 static bool
2459 queue_ids_include(const struct ovsdb_datum *queues, int64_t target)
2460 {
2461     union ovsdb_atom atom;
2462
2463     atom.integer = target;
2464     return ovsdb_datum_find_key(queues, &atom, OVSDB_TYPE_INTEGER) != UINT_MAX;
2465 }
2466
2467 static void
2468 iface_delete_queues(unsigned int queue_id,
2469                     const struct shash *details OVS_UNUSED, void *cbdata_)
2470 {
2471     struct iface_delete_queues_cbdata *cbdata = cbdata_;
2472
2473     if (!queue_ids_include(cbdata->queues, queue_id)) {
2474         netdev_delete_queue(cbdata->netdev, queue_id);
2475     }
2476 }
2477
2478 static void
2479 iface_configure_qos(struct iface *iface, const struct ovsrec_qos *qos)
2480 {
2481     if (!qos || qos->type[0] == '\0') {
2482         netdev_set_qos(iface->netdev, NULL, NULL);
2483     } else {
2484         struct iface_delete_queues_cbdata cbdata;
2485         struct shash details;
2486         size_t i;
2487
2488         /* Configure top-level Qos for 'iface'. */
2489         shash_from_ovs_idl_map(qos->key_other_config, qos->value_other_config,
2490                                qos->n_other_config, &details);
2491         netdev_set_qos(iface->netdev, qos->type, &details);
2492         shash_destroy(&details);
2493
2494         /* Deconfigure queues that were deleted. */
2495         cbdata.netdev = iface->netdev;
2496         cbdata.queues = ovsrec_qos_get_queues(qos, OVSDB_TYPE_INTEGER,
2497                                               OVSDB_TYPE_UUID);
2498         netdev_dump_queues(iface->netdev, iface_delete_queues, &cbdata);
2499
2500         /* Configure queues for 'iface'. */
2501         for (i = 0; i < qos->n_queues; i++) {
2502             const struct ovsrec_queue *queue = qos->value_queues[i];
2503             unsigned int queue_id = qos->key_queues[i];
2504
2505             shash_from_ovs_idl_map(queue->key_other_config,
2506                                    queue->value_other_config,
2507                                    queue->n_other_config, &details);
2508             netdev_set_queue(iface->netdev, queue_id, &details);
2509             shash_destroy(&details);
2510         }
2511     }
2512
2513     netdev_set_policing(iface->netdev,
2514                         iface->cfg->ingress_policing_rate,
2515                         iface->cfg->ingress_policing_burst);
2516 }
2517
2518 static void
2519 iface_configure_cfm(struct iface *iface)
2520 {
2521     size_t i;
2522     struct cfm cfm;
2523     uint16_t *remote_mps;
2524     struct ovsrec_monitor *mon;
2525     uint8_t maid[CCM_MAID_LEN];
2526
2527     mon = iface->cfg->monitor;
2528
2529     if (!mon) {
2530         ofproto_port_clear_cfm(iface->port->bridge->ofproto, iface->dp_ifidx);
2531         return;
2532     }
2533
2534     if (!cfm_generate_maid(mon->md_name, mon->ma_name, maid)) {
2535         VLOG_WARN("interface %s: Failed to generate MAID.", iface->name);
2536         return;
2537     }
2538
2539     cfm.mpid     = mon->mpid;
2540     cfm.interval = mon->interval ? *mon->interval : 1000;
2541
2542     memcpy(cfm.maid, maid, sizeof cfm.maid);
2543
2544     remote_mps = xzalloc(mon->n_remote_mps * sizeof *remote_mps);
2545     for(i = 0; i < mon->n_remote_mps; i++) {
2546         remote_mps[i] = mon->remote_mps[i]->mpid;
2547     }
2548
2549     ofproto_port_set_cfm(iface->port->bridge->ofproto, iface->dp_ifidx,
2550                          &cfm, remote_mps, mon->n_remote_mps);
2551     free(remote_mps);
2552 }
2553
2554 /* Read carrier or miimon status directly from 'iface''s netdev, according to
2555  * how 'iface''s port is configured.
2556  *
2557  * Returns true if 'iface' is up, false otherwise. */
2558 static bool
2559 iface_get_carrier(const struct iface *iface)
2560 {
2561     /* XXX */
2562     return netdev_get_carrier(iface->netdev);
2563 }
2564
2565 /* Returns true if 'iface' is synthetic, that is, if we constructed it locally
2566  * instead of obtaining it from the database. */
2567 static bool
2568 iface_is_synthetic(const struct iface *iface)
2569 {
2570     return ovsdb_idl_row_is_synthetic(&iface->cfg->header_);
2571 }
2572 \f
2573 /* Port mirroring. */
2574
2575 static struct mirror *
2576 mirror_find_by_uuid(struct bridge *br, const struct uuid *uuid)
2577 {
2578     struct mirror *m;
2579
2580     HMAP_FOR_EACH_IN_BUCKET (m, hmap_node, uuid_hash(uuid), &br->mirrors) {
2581         if (uuid_equals(uuid, &m->uuid)) {
2582             return m;
2583         }
2584     }
2585     return NULL;
2586 }
2587
2588 static void
2589 bridge_configure_mirrors(struct bridge *br)
2590 {
2591     const struct ovsdb_datum *mc;
2592     unsigned long *flood_vlans;
2593     struct mirror *m, *next;
2594     size_t i;
2595
2596     /* Get rid of deleted mirrors. */
2597     mc = ovsrec_bridge_get_mirrors(br->cfg, OVSDB_TYPE_UUID);
2598     HMAP_FOR_EACH_SAFE (m, next, hmap_node, &br->mirrors) {
2599         union ovsdb_atom atom;
2600
2601         atom.uuid = m->uuid;
2602         if (ovsdb_datum_find_key(mc, &atom, OVSDB_TYPE_UUID) == UINT_MAX) {
2603             mirror_destroy(m);
2604         }
2605     }
2606
2607     /* Add new mirrors and reconfigure existing ones. */
2608     for (i = 0; i < br->cfg->n_mirrors; i++) {
2609         const struct ovsrec_mirror *cfg = br->cfg->mirrors[i];
2610         struct mirror *m = mirror_find_by_uuid(br, &cfg->header_.uuid);
2611         if (!m) {
2612             m = mirror_create(br, cfg);
2613         }
2614         if (!mirror_configure(m, cfg)) {
2615             mirror_destroy(m);
2616         }
2617     }
2618
2619     /* Update flooded vlans (for RSPAN). */
2620     flood_vlans = vlan_bitmap_from_array(br->cfg->flood_vlans,
2621                                          br->cfg->n_flood_vlans);
2622     ofproto_set_flood_vlans(br->ofproto, flood_vlans);
2623     bitmap_free(flood_vlans);
2624 }
2625
2626 static struct mirror *
2627 mirror_create(struct bridge *br, const struct ovsrec_mirror *cfg)
2628 {
2629     struct mirror *m;
2630
2631     m = xzalloc(sizeof *m);
2632     m->uuid = cfg->header_.uuid;
2633     hmap_insert(&br->mirrors, &m->hmap_node, uuid_hash(&m->uuid));
2634     m->bridge = br;
2635     m->name = xstrdup(cfg->name);
2636
2637     return m;
2638 }
2639
2640 static void
2641 mirror_destroy(struct mirror *m)
2642 {
2643     if (m) {
2644         struct bridge *br = m->bridge;
2645
2646         if (br->ofproto) {
2647             ofproto_mirror_unregister(br->ofproto, m);
2648         }
2649
2650         hmap_remove(&br->mirrors, &m->hmap_node);
2651         free(m->name);
2652         free(m);
2653     }
2654 }
2655
2656 static void
2657 mirror_collect_ports(struct mirror *m,
2658                      struct ovsrec_port **in_ports, int n_in_ports,
2659                      void ***out_portsp, size_t *n_out_portsp)
2660 {
2661     void **out_ports = xmalloc(n_in_ports * sizeof *out_ports);
2662     size_t n_out_ports = 0;
2663     size_t i;
2664
2665     for (i = 0; i < n_in_ports; i++) {
2666         const char *name = in_ports[i]->name;
2667         struct port *port = port_lookup(m->bridge, name);
2668         if (port) {
2669             out_ports[n_out_ports++] = port;
2670         } else {
2671             VLOG_WARN("bridge %s: mirror %s cannot match on nonexistent "
2672                       "port %s", m->bridge->name, m->name, name);
2673         }
2674     }
2675     *out_portsp = out_ports;
2676     *n_out_portsp = n_out_ports;
2677 }
2678
2679 static bool
2680 mirror_configure(struct mirror *m, const struct ovsrec_mirror *cfg)
2681 {
2682     struct ofproto_mirror_settings s;
2683     struct port *out_port;
2684     struct port *port;
2685
2686     /* Set name. */
2687     if (strcmp(cfg->name, m->name)) {
2688         free(m->name);
2689         m->name = xstrdup(cfg->name);
2690     }
2691     s.name = m->name;
2692
2693     /* Get output port or VLAN. */
2694     if (cfg->output_port) {
2695         s.out_bundle = port_lookup(m->bridge, cfg->output_port->name);
2696         if (!out_port) {
2697             VLOG_ERR("bridge %s: mirror %s outputs to port not on bridge",
2698                      m->bridge->name, m->name);
2699             return false;
2700         }
2701         s.out_vlan = UINT16_MAX;
2702
2703         if (cfg->output_vlan) {
2704             VLOG_ERR("bridge %s: mirror %s specifies both output port and "
2705                      "output vlan; ignoring output vlan",
2706                      m->bridge->name, m->name);
2707         }
2708     } else if (cfg->output_vlan) {
2709         /* The database should prevent invalid VLAN values. */
2710         s.out_bundle = NULL;
2711         s.out_vlan = *cfg->output_vlan;
2712     } else {
2713         VLOG_ERR("bridge %s: mirror %s does not specify output; ignoring",
2714                  m->bridge->name, m->name);
2715         return false;
2716     }
2717
2718     /* Get port selection. */
2719     if (cfg->select_all) {
2720         size_t n_ports = hmap_count(&m->bridge->ports);
2721         void **ports = xmalloc(n_ports * sizeof *ports);
2722         size_t i;
2723
2724         i = 0;
2725         HMAP_FOR_EACH (port, hmap_node, &m->bridge->ports) {
2726             ports[i++] = port;
2727         }
2728
2729         s.srcs = ports;
2730         s.n_srcs = n_ports;
2731
2732         s.dsts = ports;
2733         s.n_dsts = n_ports;
2734     } else {
2735         /* Get ports, dropping ports that don't exist.
2736          * The IDL ensures that there are no duplicates. */
2737         mirror_collect_ports(m, cfg->select_src_port, cfg->n_select_src_port,
2738                              &s.srcs, &s.n_srcs);
2739         mirror_collect_ports(m, cfg->select_dst_port, cfg->n_select_dst_port,
2740                              &s.dsts, &s.n_dsts);
2741
2742     }
2743
2744     /* Get VLAN selection. */
2745     s.src_vlans = vlan_bitmap_from_array(cfg->select_vlan, cfg->n_select_vlan);
2746
2747     /* Configure. */
2748     ofproto_mirror_register(m->bridge->ofproto, m, &s);
2749
2750     /* Clean up. */
2751     if (s.srcs != s.dsts) {
2752         free(s.dsts);
2753     }
2754     free(s.srcs);
2755     free(s.src_vlans);
2756
2757     return true;
2758 }