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