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