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