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