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