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