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