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