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