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