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