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