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