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