ovs-brcompatd: Remove --prune-timeout option.
[sliver-openvswitch.git] / vswitchd / ovs-brcompatd.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
18 #include <asm/param.h>
19 #include <assert.h>
20 #include <errno.h>
21 #include <getopt.h>
22 #include <inttypes.h>
23 #include <limits.h>
24 #include <net/if.h>
25 #include <linux/genetlink.h>
26 #include <linux/rtnetlink.h>
27 #include <signal.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <sys/types.h>
31 #include <sys/stat.h>
32 #include <time.h>
33 #include <fcntl.h>
34 #include <unistd.h>
35
36 #include "command-line.h"
37 #include "coverage.h"
38 #include "daemon.h"
39 #include "dirs.h"
40 #include "dynamic-string.h"
41 #include "fatal-signal.h"
42 #include "json.h"
43 #include "leak-checker.h"
44 #include "netdev.h"
45 #include "netlink.h"
46 #include "netlink-socket.h"
47 #include "ofpbuf.h"
48 #include "openvswitch/brcompat-netlink.h"
49 #include "ovsdb-idl.h"
50 #include "packets.h"
51 #include "poll-loop.h"
52 #include "process.h"
53 #include "rtnetlink.h"
54 #include "rtnetlink-link.h"
55 #include "signals.h"
56 #include "sset.h"
57 #include "timeval.h"
58 #include "unixctl.h"
59 #include "util.h"
60 #include "vlog.h"
61 #include "vswitchd/vswitch-idl.h"
62
63 VLOG_DEFINE_THIS_MODULE(brcompatd);
64
65
66 /* xxx Just hangs if datapath is rmmod/insmod.  Learn to reconnect? */
67
68 /* Actions to modify bridge compatibility configuration. */
69 enum bmc_action {
70     BMC_ADD_DP,
71     BMC_DEL_DP,
72     BMC_ADD_PORT,
73     BMC_DEL_PORT
74 };
75
76 static const char *parse_options(int argc, char *argv[]);
77 static void usage(void) NO_RETURN;
78
79 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 60);
80
81 /* Shell command to execute (via popen()) to send a control command to the
82  * running ovs-vswitchd process.  The string must contain one instance of %s,
83  * which is replaced by the control command. */
84 static char *appctl_command;
85
86 /* Netlink socket to bridge compatibility kernel module. */
87 static struct nl_sock *brc_sock;
88
89 /* The Generic Netlink family number used for bridge compatibility. */
90 static int brc_family;
91
92 static const struct nl_policy brc_multicast_policy[] = {
93     [BRC_GENL_A_MC_GROUP] = {.type = NL_A_U32 }
94 };
95
96 static int
97 lookup_brc_multicast_group(int *multicast_group)
98 {
99     struct nl_sock *sock;
100     struct ofpbuf request, *reply;
101     struct nlattr *attrs[ARRAY_SIZE(brc_multicast_policy)];
102     int retval;
103
104     retval = nl_sock_create(NETLINK_GENERIC, &sock);
105     if (retval) {
106         return retval;
107     }
108     ofpbuf_init(&request, 0);
109     nl_msg_put_genlmsghdr(&request, 0, brc_family,
110             NLM_F_REQUEST, BRC_GENL_C_QUERY_MC, 1);
111     retval = nl_sock_transact(sock, &request, &reply);
112     ofpbuf_uninit(&request);
113     if (retval) {
114         nl_sock_destroy(sock);
115         return retval;
116     }
117     if (!nl_policy_parse(reply, NLMSG_HDRLEN + GENL_HDRLEN,
118                          brc_multicast_policy, attrs,
119                          ARRAY_SIZE(brc_multicast_policy))) {
120         nl_sock_destroy(sock);
121         ofpbuf_delete(reply);
122         return EPROTO;
123     }
124     *multicast_group = nl_attr_get_u32(attrs[BRC_GENL_A_MC_GROUP]);
125     nl_sock_destroy(sock);
126     ofpbuf_delete(reply);
127
128     return 0;
129 }
130
131 /* Opens a socket for brcompat notifications.  Returns 0 if successful,
132  * otherwise a positive errno value. */
133 static int
134 brc_open(struct nl_sock **sock)
135 {
136     int multicast_group = 0;
137     int retval;
138
139     retval = nl_lookup_genl_family(BRC_GENL_FAMILY_NAME, &brc_family);
140     if (retval) {
141         return retval;
142     }
143
144     retval = lookup_brc_multicast_group(&multicast_group);
145     if (retval) {
146         return retval;
147     }
148
149     retval = nl_sock_create(NETLINK_GENERIC, sock);
150     if (retval) {
151         return retval;
152     }
153
154     retval = nl_sock_join_mcgroup(*sock, multicast_group);
155     if (retval) {
156         nl_sock_destroy(*sock);
157         *sock = NULL;
158     }
159     return retval;
160 }
161
162 static const struct nl_policy brc_dp_policy[] = {
163     [BRC_GENL_A_DP_NAME] = { .type = NL_A_STRING },
164 };
165
166 static struct ovsrec_bridge *
167 find_bridge(const struct ovsrec_open_vswitch *ovs, const char *br_name)
168 {
169     size_t i;
170
171     for (i = 0; i < ovs->n_bridges; i++) {
172         if (!strcmp(br_name, ovs->bridges[i]->name)) {
173             return ovs->bridges[i];
174         }
175     }
176
177     return NULL;
178 }
179
180 static int
181 execute_appctl_command(const char *unixctl_command, char **output)
182 {
183     char *stdout_log, *stderr_log;
184     int error, status;
185     char *argv[5];
186
187     argv[0] = "/bin/sh";
188     argv[1] = "-c";
189     argv[2] = xasprintf(appctl_command, unixctl_command);
190     argv[3] = NULL;
191
192     /* Run process and log status. */
193     error = process_run_capture(argv, &stdout_log, &stderr_log, 65536,
194                                 &status);
195     if (error) {
196         VLOG_ERR("failed to execute %s command via ovs-appctl: %s",
197                  unixctl_command, strerror(error));
198     } else if (status) {
199         char *msg = process_status_msg(status);
200         VLOG_ERR("ovs-appctl exited with error (%s)", msg);
201         free(msg);
202         error = ECHILD;
203     }
204
205     /* Deal with stdout_log. */
206     if (output) {
207         *output = stdout_log;
208     } else {
209         free(stdout_log);
210     }
211
212     /* Deal with stderr_log */
213     if (stderr_log && *stderr_log) {
214         VLOG_INFO("ovs-appctl wrote to stderr:\n%s", stderr_log);
215     }
216     free(stderr_log);
217
218     free(argv[2]);
219
220     return error;
221 }
222
223 static void
224 do_get_bridge_parts(const struct ovsrec_bridge *br, struct sset *parts,
225                     int vlan, bool break_down_bonds)
226 {
227     size_t i, j;
228
229     for (i = 0; i < br->n_ports; i++) {
230         const struct ovsrec_port *port = br->ports[i];
231
232         if (vlan >= 0) {
233             int port_vlan = port->n_tag ? *port->tag : 0;
234             if (vlan != port_vlan) {
235                 continue;
236             }
237         }
238         if (break_down_bonds) {
239             for (j = 0; j < port->n_interfaces; j++) {
240                 const struct ovsrec_interface *iface = port->interfaces[j];
241                 sset_add(parts, iface->name);
242             }
243         } else {
244             sset_add(parts, port->name);
245         }
246     }
247 }
248
249 /* Add all the interfaces for 'bridge' to 'ifaces', breaking bonded interfaces
250  * down into their constituent parts.
251  *
252  * If 'vlan' < 0, all interfaces on 'bridge' are reported.  If 'vlan' == 0,
253  * then only interfaces for trunk ports or ports with implicit VLAN 0 are
254  * reported.  If 'vlan' > 0, only interfaces with implicit VLAN 'vlan' are
255  * reported.  */
256 static void
257 get_bridge_ifaces(const struct ovsrec_bridge *br, struct sset *ifaces,
258                   int vlan)
259 {
260     do_get_bridge_parts(br, ifaces, vlan, true);
261 }
262
263 /* Add all the ports for 'bridge' to 'ports'.  Bonded ports are reported under
264  * the bond name, not broken down into their constituent interfaces.
265  *
266  * If 'vlan' < 0, all ports on 'bridge' are reported.  If 'vlan' == 0, then
267  * only trunk ports or ports with implicit VLAN 0 are reported.  If 'vlan' > 0,
268  * only port with implicit VLAN 'vlan' are reported.  */
269 static void
270 get_bridge_ports(const struct ovsrec_bridge *br, struct sset *ports,
271                  int vlan)
272 {
273     do_get_bridge_parts(br, ports, vlan, false);
274 }
275
276 static struct ovsdb_idl_txn *
277 txn_from_openvswitch(const struct ovsrec_open_vswitch *ovs)
278 {
279     return ovsdb_idl_txn_get(&ovs->header_);
280 }
281
282 static bool
283 port_is_fake_bridge(const struct ovsrec_port *port)
284 {
285     return (port->fake_bridge
286             && port->tag
287             && *port->tag >= 1 && *port->tag <= 4095);
288 }
289
290 static void
291 ovs_insert_bridge(const struct ovsrec_open_vswitch *ovs,
292                   struct ovsrec_bridge *bridge)
293 {
294     struct ovsrec_bridge **bridges;
295     size_t i;
296
297     bridges = xmalloc(sizeof *ovs->bridges * (ovs->n_bridges + 1));
298     for (i = 0; i < ovs->n_bridges; i++) {
299         bridges[i] = ovs->bridges[i];
300     }
301     bridges[ovs->n_bridges] = bridge;
302     ovsrec_open_vswitch_set_bridges(ovs, bridges, ovs->n_bridges + 1);
303     free(bridges);
304 }
305
306 static struct json *
307 where_uuid_equals(const struct uuid *uuid)
308 {
309     return
310         json_array_create_1(
311             json_array_create_3(
312                 json_string_create("_uuid"),
313                 json_string_create("=="),
314                 json_array_create_2(
315                     json_string_create("uuid"),
316                     json_string_create_nocopy(
317                         xasprintf(UUID_FMT, UUID_ARGS(uuid))))));
318 }
319
320 /* Commits 'txn'.  If 'wait_for_reload' is true, also waits for Open vSwitch to
321    reload the configuration before returning.
322
323    Returns EAGAIN if the caller should try the operation again, 0 on success,
324    otherwise a positive errno value. */
325 static int
326 commit_txn(struct ovsdb_idl_txn *txn, bool wait_for_reload)
327 {
328     struct ovsdb_idl *idl = ovsdb_idl_txn_get_idl (txn);
329     enum ovsdb_idl_txn_status status;
330     int64_t next_cfg = 0;
331
332     if (wait_for_reload) {
333         const struct ovsrec_open_vswitch *ovs = ovsrec_open_vswitch_first(idl);
334         struct json *where = where_uuid_equals(&ovs->header_.uuid);
335         ovsdb_idl_txn_increment(txn, "Open_vSwitch", "next_cfg", where);
336         json_destroy(where);
337     }
338     status = ovsdb_idl_txn_commit_block(txn);
339     if (wait_for_reload && status == TXN_SUCCESS) {
340         next_cfg = ovsdb_idl_txn_get_increment_new_value(txn);
341     }
342     ovsdb_idl_txn_destroy(txn);
343
344     switch (status) {
345     case TXN_INCOMPLETE:
346         NOT_REACHED();
347
348     case TXN_ABORTED:
349         VLOG_ERR_RL(&rl, "OVSDB transaction unexpectedly aborted");
350         return ECONNABORTED;
351
352     case TXN_UNCHANGED:
353         return 0;
354
355     case TXN_SUCCESS:
356         if (wait_for_reload) {
357             for (;;) {
358                 /* We can't use 'ovs' any longer because ovsdb_idl_run() can
359                  * destroy it. */
360                 const struct ovsrec_open_vswitch *ovs2;
361
362                 ovsdb_idl_run(idl);
363                 OVSREC_OPEN_VSWITCH_FOR_EACH (ovs2, idl) {
364                     if (ovs2->cur_cfg >= next_cfg) {
365                         goto done;
366                     }
367                 }
368                 ovsdb_idl_wait(idl);
369                 poll_block();
370             }
371         done: ;
372         }
373         return 0;
374
375     case TXN_TRY_AGAIN:
376         VLOG_ERR_RL(&rl, "OVSDB transaction needs retry");
377         return EAGAIN;
378
379     case TXN_ERROR:
380         VLOG_ERR_RL(&rl, "OVSDB transaction failed: %s",
381                     ovsdb_idl_txn_get_error(txn));
382         return EBUSY;
383
384     default:
385         NOT_REACHED();
386     }
387 }
388
389 static int
390 add_bridge(struct ovsdb_idl *idl, const struct ovsrec_open_vswitch *ovs,
391            const char *br_name)
392 {
393     struct ovsrec_bridge *br;
394     struct ovsrec_port *port;
395     struct ovsrec_interface *iface;
396     struct ovsdb_idl_txn *txn;
397
398     if (find_bridge(ovs, br_name)) {
399         VLOG_WARN("addbr %s: bridge %s exists", br_name, br_name);
400         return EEXIST;
401     } else if (netdev_exists(br_name)) {
402         size_t i;
403
404         for (i = 0; i < ovs->n_bridges; i++) {
405             size_t j;
406             struct ovsrec_bridge *br_cfg = ovs->bridges[i];
407
408             for (j = 0; j < br_cfg->n_ports; j++) {
409                 if (port_is_fake_bridge(br_cfg->ports[j])) {
410                     VLOG_WARN("addbr %s: %s exists as a fake bridge",
411                               br_name, br_name);
412                     return 0;
413                 }
414             }
415         }
416
417         VLOG_WARN("addbr %s: cannot create bridge %s because a network "
418                   "device named %s already exists",
419                   br_name, br_name, br_name);
420         return EEXIST;
421     }
422
423     txn = ovsdb_idl_txn_create(idl);
424
425     ovsdb_idl_txn_add_comment(txn, "ovs-brcompatd: addbr %s", br_name);
426
427     iface = ovsrec_interface_insert(txn_from_openvswitch(ovs));
428     ovsrec_interface_set_name(iface, br_name);
429
430     port = ovsrec_port_insert(txn_from_openvswitch(ovs));
431     ovsrec_port_set_name(port, br_name);
432     ovsrec_port_set_interfaces(port, &iface, 1);
433
434     br = ovsrec_bridge_insert(txn_from_openvswitch(ovs));
435     ovsrec_bridge_set_name(br, br_name);
436     ovsrec_bridge_set_ports(br, &port, 1);
437
438     ovs_insert_bridge(ovs, br);
439
440     return commit_txn(txn, true);
441 }
442
443 static void
444 add_port(const struct ovsrec_open_vswitch *ovs,
445          const struct ovsrec_bridge *br, const char *port_name)
446 {
447     struct ovsrec_interface *iface;
448     struct ovsrec_port *port;
449     struct ovsrec_port **ports;
450     size_t i;
451
452     /* xxx Check conflicts? */
453     iface = ovsrec_interface_insert(txn_from_openvswitch(ovs));
454     ovsrec_interface_set_name(iface, port_name);
455
456     port = ovsrec_port_insert(txn_from_openvswitch(ovs));
457     ovsrec_port_set_name(port, port_name);
458     ovsrec_port_set_interfaces(port, &iface, 1);
459
460     ports = xmalloc(sizeof *br->ports * (br->n_ports + 1));
461     for (i = 0; i < br->n_ports; i++) {
462         ports[i] = br->ports[i];
463     }
464     ports[br->n_ports] = port;
465     ovsrec_bridge_set_ports(br, ports, br->n_ports + 1);
466     free(ports);
467 }
468
469 /* Deletes 'port' from 'br'.
470  *
471  * After calling this function, 'port' must not be referenced again. */
472 static void
473 del_port(const struct ovsrec_bridge *br, const struct ovsrec_port *port)
474 {
475     struct ovsrec_port **ports;
476     size_t i, n;
477
478     /* Remove 'port' from the bridge's list of ports. */
479     ports = xmalloc(sizeof *br->ports * br->n_ports);
480     for (i = n = 0; i < br->n_ports; i++) {
481         if (br->ports[i] != port) {
482             ports[n++] = br->ports[i];
483         }
484     }
485     ovsrec_bridge_set_ports(br, ports, n);
486     free(ports);
487 }
488
489 /* Delete 'iface' from 'port' (which must be within 'br').  If 'iface' was
490  * 'port''s only interface, delete 'port' from 'br' also.
491  *
492  * After calling this function, 'iface' must not be referenced again. */
493 static void
494 del_interface(const struct ovsrec_bridge *br,
495               const struct ovsrec_port *port,
496               const struct ovsrec_interface *iface)
497 {
498     if (port->n_interfaces == 1) {
499         del_port(br, port);
500     } else {
501         struct ovsrec_interface **ifaces;
502         size_t i, n;
503
504         ifaces = xmalloc(sizeof *port->interfaces * port->n_interfaces);
505         for (i = n = 0; i < port->n_interfaces; i++) {
506             if (port->interfaces[i] != iface) {
507                 ifaces[n++] = port->interfaces[i];
508             }
509         }
510         ovsrec_port_set_interfaces(port, ifaces, n);
511         free(ifaces);
512     }
513 }
514
515 /* Find and return a port within 'br' named 'port_name'. */
516 static const struct ovsrec_port *
517 find_port(const struct ovsrec_bridge *br, const char *port_name)
518 {
519     size_t i;
520
521     for (i = 0; i < br->n_ports; i++) {
522         struct ovsrec_port *port = br->ports[i];
523         if (!strcmp(port_name, port->name)) {
524             return port;
525         }
526     }
527     return NULL;
528 }
529
530 /* Find and return an interface within 'br' named 'iface_name'. */
531 static const struct ovsrec_interface *
532 find_interface(const struct ovsrec_bridge *br, const char *iface_name,
533                struct ovsrec_port **portp)
534 {
535     size_t i;
536
537     for (i = 0; i < br->n_ports; i++) {
538         struct ovsrec_port *port = br->ports[i];
539         size_t j;
540
541         for (j = 0; j < port->n_interfaces; j++) {
542             struct ovsrec_interface *iface = port->interfaces[j];
543             if (!strcmp(iface->name, iface_name)) {
544                 *portp = port;
545                 return iface;
546             }
547         }
548     }
549
550     *portp = NULL;
551     return NULL;
552 }
553
554 static int
555 del_bridge(struct ovsdb_idl *idl,
556            const struct ovsrec_open_vswitch *ovs, const char *br_name)
557 {
558     struct ovsrec_bridge *br = find_bridge(ovs, br_name);
559     struct ovsrec_bridge **bridges;
560     struct ovsdb_idl_txn *txn;
561     size_t i, n;
562
563     if (!br) {
564         VLOG_WARN("delbr %s: no bridge named %s", br_name, br_name);
565         return ENXIO;
566     }
567
568     txn = ovsdb_idl_txn_create(idl);
569
570     ovsdb_idl_txn_add_comment(txn, "ovs-brcompatd: delbr %s", br_name);
571
572     /* Remove 'br' from the vswitch's list of bridges. */
573     bridges = xmalloc(sizeof *ovs->bridges * ovs->n_bridges);
574     for (i = n = 0; i < ovs->n_bridges; i++) {
575         if (ovs->bridges[i] != br) {
576             bridges[n++] = ovs->bridges[i];
577         }
578     }
579     ovsrec_open_vswitch_set_bridges(ovs, bridges, n);
580     free(bridges);
581
582     return commit_txn(txn, true);
583 }
584
585 static int
586 parse_command(struct ofpbuf *buffer, uint32_t *seq, const char **br_name,
587               const char **port_name, uint64_t *count, uint64_t *skip)
588 {
589     static const struct nl_policy policy[] = {
590         [BRC_GENL_A_DP_NAME] = { .type = NL_A_STRING, .optional = true },
591         [BRC_GENL_A_PORT_NAME] = { .type = NL_A_STRING, .optional = true },
592         [BRC_GENL_A_FDB_COUNT] = { .type = NL_A_U64, .optional = true },
593         [BRC_GENL_A_FDB_SKIP] = { .type = NL_A_U64, .optional = true },
594     };
595     struct nlattr *attrs[ARRAY_SIZE(policy)];
596
597     if (!nl_policy_parse(buffer, NLMSG_HDRLEN + GENL_HDRLEN, policy,
598                          attrs, ARRAY_SIZE(policy))
599         || (br_name && !attrs[BRC_GENL_A_DP_NAME])
600         || (port_name && !attrs[BRC_GENL_A_PORT_NAME])
601         || (count && !attrs[BRC_GENL_A_FDB_COUNT])
602         || (skip && !attrs[BRC_GENL_A_FDB_SKIP])) {
603         return EINVAL;
604     }
605
606     *seq = ((struct nlmsghdr *) buffer->data)->nlmsg_seq;
607     if (br_name) {
608         *br_name = nl_attr_get_string(attrs[BRC_GENL_A_DP_NAME]);
609     }
610     if (port_name) {
611         *port_name = nl_attr_get_string(attrs[BRC_GENL_A_PORT_NAME]);
612     }
613     if (count) {
614         *count = nl_attr_get_u64(attrs[BRC_GENL_A_FDB_COUNT]);
615     }
616     if (skip) {
617         *skip = nl_attr_get_u64(attrs[BRC_GENL_A_FDB_SKIP]);
618     }
619     return 0;
620 }
621
622 /* Composes and returns a reply to a request made by the datapath with Netlink
623  * sequence number 'seq' and error code 'error'.  The caller may add additional
624  * attributes to the message, then it may send it with send_reply(). */
625 static struct ofpbuf *
626 compose_reply(uint32_t seq, int error)
627 {
628     struct ofpbuf *reply = ofpbuf_new(4096);
629     nl_msg_put_genlmsghdr(reply, 32, brc_family, NLM_F_REQUEST,
630                           BRC_GENL_C_DP_RESULT, 1);
631     ((struct nlmsghdr *) reply->data)->nlmsg_seq = seq;
632     nl_msg_put_u32(reply, BRC_GENL_A_ERR_CODE, error);
633     return reply;
634 }
635
636 /* Sends 'reply' to the datapath and frees it. */
637 static void
638 send_reply(struct ofpbuf *reply)
639 {
640     int retval = nl_sock_send(brc_sock, reply, false);
641     if (retval) {
642         VLOG_WARN_RL(&rl, "replying to brcompat request: %s",
643                      strerror(retval));
644     }
645     ofpbuf_delete(reply);
646 }
647
648 /* Composes and sends a reply to a request made by the datapath with Netlink
649  * sequence number 'seq' and error code 'error'. */
650 static void
651 send_simple_reply(uint32_t seq, int error)
652 {
653     send_reply(compose_reply(seq, error));
654 }
655
656 static int
657 handle_bridge_cmd(struct ovsdb_idl *idl,
658                   const struct ovsrec_open_vswitch *ovs,
659                   struct ofpbuf *buffer, bool add)
660 {
661     const char *br_name;
662     uint32_t seq;
663     int error;
664
665     error = parse_command(buffer, &seq, &br_name, NULL, NULL, NULL);
666     if (!error) {
667         int retval;
668
669         do {
670             retval = (add ? add_bridge : del_bridge)(idl, ovs, br_name);
671             VLOG_INFO_RL(&rl, "%sbr %s: %s",
672                          add ? "add" : "del", br_name, strerror(retval));
673         } while (retval == EAGAIN);
674
675         send_simple_reply(seq, error);
676     }
677     return error;
678 }
679
680 static const struct nl_policy brc_port_policy[] = {
681     [BRC_GENL_A_DP_NAME] = { .type = NL_A_STRING },
682     [BRC_GENL_A_PORT_NAME] = { .type = NL_A_STRING },
683 };
684
685 static int
686 handle_port_cmd(struct ovsdb_idl *idl,
687                 const struct ovsrec_open_vswitch *ovs,
688                 struct ofpbuf *buffer, bool add)
689 {
690     const char *cmd_name = add ? "add-if" : "del-if";
691     const char *br_name, *port_name;
692     uint32_t seq;
693     int error;
694
695     error = parse_command(buffer, &seq, &br_name, &port_name, NULL, NULL);
696     if (!error) {
697         struct ovsrec_bridge *br = find_bridge(ovs, br_name);
698
699         if (!br) {
700             VLOG_WARN("%s %s %s: no bridge named %s",
701                       cmd_name, br_name, port_name, br_name);
702             error = EINVAL;
703         } else if (!netdev_exists(port_name)) {
704             VLOG_WARN("%s %s %s: no network device named %s",
705                       cmd_name, br_name, port_name, port_name);
706             error = EINVAL;
707         } else {
708             do {
709                 struct ovsdb_idl_txn *txn = ovsdb_idl_txn_create(idl);
710
711                 if (add) {
712                     ovsdb_idl_txn_add_comment(txn, "ovs-brcompatd: add-if %s",
713                                               port_name);
714                     add_port(ovs, br, port_name);
715                 } else {
716                     const struct ovsrec_port *port = find_port(br, port_name);
717                     if (port) {
718                         ovsdb_idl_txn_add_comment(txn,
719                                                   "ovs-brcompatd: del-if %s",
720                                                   port_name);
721                         del_port(br, port);
722                     }
723                 }
724
725                 error = commit_txn(txn, true);
726                 VLOG_INFO_RL(&rl, "%s %s %s: %s",
727                              cmd_name, br_name, port_name, strerror(error));
728             } while (error == EAGAIN);
729         }
730         send_simple_reply(seq, error);
731     }
732
733     return error;
734 }
735
736 /* The caller is responsible for freeing '*ovs_name' if the call is
737  * successful. */
738 static int
739 linux_bridge_to_ovs_bridge(const struct ovsrec_open_vswitch *ovs,
740                            const char *linux_name,
741                            const struct ovsrec_bridge **ovs_bridge,
742                            int *br_vlan)
743 {
744     *ovs_bridge = find_bridge(ovs, linux_name);
745     if (*ovs_bridge) {
746         /* Bridge name is the same.  We are interested in VLAN 0. */
747         *br_vlan = 0;
748         return 0;
749     } else {
750         /* No such Open vSwitch bridge 'linux_name', but there might be an
751          * internal port named 'linux_name' on some other bridge
752          * 'ovs_bridge'.  If so then we are interested in the VLAN assigned to
753          * port 'linux_name' on the bridge named 'ovs_bridge'. */
754         size_t i, j;
755
756         for (i = 0; i < ovs->n_bridges; i++) {
757             const struct ovsrec_bridge *br = ovs->bridges[i];
758
759             for (j = 0; j < br->n_ports; j++) {
760                 const struct ovsrec_port *port = br->ports[j];
761
762                 if (!strcmp(port->name, linux_name)) {
763                     *ovs_bridge = br;
764                     *br_vlan = port->n_tag ? *port->tag : -1;
765                     return 0;
766                 }
767             }
768
769         }
770         return ENODEV;
771     }
772 }
773
774 static int
775 handle_fdb_query_cmd(const struct ovsrec_open_vswitch *ovs,
776                      struct ofpbuf *buffer)
777 {
778     /* This structure is copied directly from the Linux 2.6.30 header files.
779      * It would be more straightforward to #include <linux/if_bridge.h>, but
780      * the 'port_hi' member was only introduced in Linux 2.6.26 and so systems
781      * with old header files won't have it. */
782     struct __fdb_entry {
783         __u8 mac_addr[6];
784         __u8 port_no;
785         __u8 is_local;
786         __u32 ageing_timer_value;
787         __u8 port_hi;
788         __u8 pad0;
789         __u16 unused;
790     };
791
792     struct mac {
793         uint8_t addr[6];
794     };
795     struct mac *local_macs;
796     int n_local_macs;
797     int i;
798
799     /* Impedance matching between the vswitchd and Linux kernel notions of what
800      * a bridge is.  The kernel only handles a single VLAN per bridge, but
801      * vswitchd can deal with all the VLANs on a single bridge.  We have to
802      * pretend that the former is the case even though the latter is the
803      * implementation. */
804     const char *linux_name;   /* Name used by brctl. */
805     const struct ovsrec_bridge *ovs_bridge;  /* Bridge used by ovs-vswitchd. */
806     int br_vlan;                /* VLAN tag. */
807     struct sset ifaces;
808
809     struct ofpbuf query_data;
810     const char *iface_name;
811     struct ofpbuf *reply;
812     char *unixctl_command;
813     uint64_t count, skip;
814     char *output;
815     char *save_ptr;
816     uint32_t seq;
817     int error;
818
819     /* Parse the command received from brcompat_mod. */
820     error = parse_command(buffer, &seq, &linux_name, NULL, &count, &skip);
821     if (error) {
822         return error;
823     }
824
825     /* Figure out vswitchd bridge and VLAN. */
826     error = linux_bridge_to_ovs_bridge(ovs, linux_name,
827                                        &ovs_bridge, &br_vlan);
828     if (error) {
829         send_simple_reply(seq, error);
830         return error;
831     }
832
833     /* Fetch the forwarding database using ovs-appctl. */
834     unixctl_command = xasprintf("fdb/show %s", ovs_bridge->name);
835     error = execute_appctl_command(unixctl_command, &output);
836     free(unixctl_command);
837     if (error) {
838         send_simple_reply(seq, error);
839         return error;
840     }
841
842     /* Fetch the MAC address for each interface on the bridge, so that we can
843      * fill in the is_local field in the response. */
844     sset_init(&ifaces);
845     get_bridge_ifaces(ovs_bridge, &ifaces, br_vlan);
846     local_macs = xmalloc(sset_count(&ifaces) * sizeof *local_macs);
847     n_local_macs = 0;
848     SSET_FOR_EACH (iface_name, &ifaces) {
849         struct mac *mac = &local_macs[n_local_macs];
850         struct netdev *netdev;
851
852         error = netdev_open_default(iface_name, &netdev);
853         if (!error) {
854             if (!netdev_get_etheraddr(netdev, mac->addr)) {
855                 n_local_macs++;
856             }
857             netdev_close(netdev);
858         }
859     }
860     sset_destroy(&ifaces);
861
862     /* Parse the response from ovs-appctl and convert it to binary format to
863      * pass back to the kernel. */
864     ofpbuf_init(&query_data, sizeof(struct __fdb_entry) * 8);
865     save_ptr = NULL;
866     strtok_r(output, "\n", &save_ptr); /* Skip header line. */
867     while (count > 0) {
868         struct __fdb_entry *entry;
869         int port, vlan, age;
870         uint8_t mac[ETH_ADDR_LEN];
871         char *line;
872         bool is_local;
873
874         line = strtok_r(NULL, "\n", &save_ptr);
875         if (!line) {
876             break;
877         }
878
879         if (sscanf(line, "%d %d "ETH_ADDR_SCAN_FMT" %d",
880                    &port, &vlan, ETH_ADDR_SCAN_ARGS(mac), &age)
881             != 2 + ETH_ADDR_SCAN_COUNT + 1) {
882             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 1);
883             VLOG_INFO_RL(&rl, "fdb/show output has invalid format: %s", line);
884             continue;
885         }
886
887         if (vlan != br_vlan) {
888             continue;
889         }
890
891         if (skip > 0) {
892             skip--;
893             continue;
894         }
895
896         /* Is this the MAC address of an interface on the bridge? */
897         is_local = false;
898         for (i = 0; i < n_local_macs; i++) {
899             if (eth_addr_equals(local_macs[i].addr, mac)) {
900                 is_local = true;
901                 break;
902             }
903         }
904
905         entry = ofpbuf_put_uninit(&query_data, sizeof *entry);
906         memcpy(entry->mac_addr, mac, ETH_ADDR_LEN);
907         entry->port_no = port & 0xff;
908         entry->is_local = is_local;
909         entry->ageing_timer_value = age * HZ;
910         entry->port_hi = (port & 0xff00) >> 8;
911         entry->pad0 = 0;
912         entry->unused = 0;
913         count--;
914     }
915     free(output);
916
917     /* Compose and send reply to datapath. */
918     reply = compose_reply(seq, 0);
919     nl_msg_put_unspec(reply, BRC_GENL_A_FDB_DATA,
920                       query_data.data, query_data.size);
921     send_reply(reply);
922
923     /* Free memory. */
924     ofpbuf_uninit(&query_data);
925     free(local_macs);
926
927     return 0;
928 }
929
930 static void
931 send_ifindex_reply(uint32_t seq, struct sset *ifaces)
932 {
933     struct ofpbuf *reply;
934     const char *iface;
935     size_t n_indices;
936     int *indices;
937
938     /* Convert 'ifaces' into ifindexes. */
939     n_indices = 0;
940     indices = xmalloc(sset_count(ifaces) * sizeof *indices);
941     SSET_FOR_EACH (iface, ifaces) {
942         int ifindex = if_nametoindex(iface);
943         if (ifindex) {
944             indices[n_indices++] = ifindex;
945         }
946     }
947
948     /* Compose and send reply. */
949     reply = compose_reply(seq, 0);
950     nl_msg_put_unspec(reply, BRC_GENL_A_IFINDEXES,
951                       indices, n_indices * sizeof *indices);
952     send_reply(reply);
953
954     /* Free memory. */
955     free(indices);
956 }
957
958 static int
959 handle_get_bridges_cmd(const struct ovsrec_open_vswitch *ovs,
960                        struct ofpbuf *buffer)
961 {
962     struct sset bridges;
963     size_t i, j;
964
965     uint32_t seq;
966
967     int error;
968
969     /* Parse Netlink command.
970      *
971      * The command doesn't actually have any arguments, but we need the
972      * sequence number to send the reply. */
973     error = parse_command(buffer, &seq, NULL, NULL, NULL, NULL);
974     if (error) {
975         return error;
976     }
977
978     /* Get all the real bridges and all the fake ones. */
979     sset_init(&bridges);
980     for (i = 0; i < ovs->n_bridges; i++) {
981         const struct ovsrec_bridge *br = ovs->bridges[i];
982
983         sset_add(&bridges, br->name);
984         for (j = 0; j < br->n_ports; j++) {
985             const struct ovsrec_port *port = br->ports[j];
986
987             if (port->fake_bridge) {
988                 sset_add(&bridges, port->name);
989             }
990         }
991     }
992
993     send_ifindex_reply(seq, &bridges);
994     sset_destroy(&bridges);
995
996     return 0;
997 }
998
999 static int
1000 handle_get_ports_cmd(const struct ovsrec_open_vswitch *ovs,
1001                      struct ofpbuf *buffer)
1002 {
1003     uint32_t seq;
1004
1005     const char *linux_name;
1006     const struct ovsrec_bridge *ovs_bridge;
1007     int br_vlan;
1008
1009     struct sset ports;
1010
1011     int error;
1012
1013     /* Parse Netlink command. */
1014     error = parse_command(buffer, &seq, &linux_name, NULL, NULL, NULL);
1015     if (error) {
1016         return error;
1017     }
1018
1019     error = linux_bridge_to_ovs_bridge(ovs, linux_name,
1020                                        &ovs_bridge, &br_vlan);
1021     if (error) {
1022         send_simple_reply(seq, error);
1023         return error;
1024     }
1025
1026     sset_init(&ports);
1027     get_bridge_ports(ovs_bridge, &ports, br_vlan);
1028     sset_find_and_delete(&ports, linux_name);
1029     send_ifindex_reply(seq, &ports); /* XXX bonds won't show up */
1030     sset_destroy(&ports);
1031
1032     return 0;
1033 }
1034
1035 static struct ofpbuf *
1036 brc_recv_update__(void)
1037 {
1038     for (;;) {
1039         struct ofpbuf *buffer;
1040         int retval;
1041
1042         retval = nl_sock_recv(brc_sock, &buffer, false);
1043         switch (retval) {
1044         case 0:
1045             if (nl_msg_nlmsgerr(buffer, NULL)
1046                 || nl_msg_nlmsghdr(buffer)->nlmsg_type == NLMSG_DONE) {
1047                 break;
1048             }
1049             return buffer;
1050
1051         case ENOBUFS:
1052             break;
1053
1054         case EAGAIN:
1055             return NULL;
1056
1057         default:
1058             VLOG_WARN_RL(&rl, "brc_recv_update: %s", strerror(retval));
1059             return NULL;
1060         }
1061         ofpbuf_delete(buffer);
1062     }
1063 }
1064
1065 static void
1066 brc_recv_update(struct ovsdb_idl *idl)
1067 {
1068     struct ofpbuf *buffer;
1069     struct genlmsghdr *genlmsghdr;
1070     const struct ovsrec_open_vswitch *ovs;
1071
1072     buffer = brc_recv_update__();
1073     if (!buffer) {
1074         return;
1075     }
1076
1077     genlmsghdr = nl_msg_genlmsghdr(buffer);
1078     if (!genlmsghdr) {
1079         VLOG_WARN_RL(&rl, "received packet too short for generic NetLink");
1080         goto error;
1081     }
1082
1083     if (nl_msg_nlmsghdr(buffer)->nlmsg_type != brc_family) {
1084         VLOG_DBG_RL(&rl, "received type (%"PRIu16") != brcompat family (%d)",
1085                 nl_msg_nlmsghdr(buffer)->nlmsg_type, brc_family);
1086         goto error;
1087     }
1088
1089     /* Get the Open vSwitch configuration.  Just drop the request on the floor
1090      * if a valid configuration doesn't exist.  (We could check this earlier,
1091      * but we want to drain pending Netlink messages even when there is no Open
1092      * vSwitch configuration.) */
1093     ovs = ovsrec_open_vswitch_first(idl);
1094     if (!ovs) {
1095         VLOG_WARN_RL(&rl, "could not find valid configuration to update");
1096         goto error;
1097     }
1098
1099     switch (genlmsghdr->cmd) {
1100     case BRC_GENL_C_DP_ADD:
1101         handle_bridge_cmd(idl, ovs, buffer, true);
1102         break;
1103
1104     case BRC_GENL_C_DP_DEL:
1105         handle_bridge_cmd(idl, ovs, buffer, false);
1106         break;
1107
1108     case BRC_GENL_C_PORT_ADD:
1109         handle_port_cmd(idl, ovs, buffer, true);
1110         break;
1111
1112     case BRC_GENL_C_PORT_DEL:
1113         handle_port_cmd(idl, ovs, buffer, false);
1114         break;
1115
1116     case BRC_GENL_C_FDB_QUERY:
1117         handle_fdb_query_cmd(ovs, buffer);
1118         break;
1119
1120     case BRC_GENL_C_GET_BRIDGES:
1121         handle_get_bridges_cmd(ovs, buffer);
1122         break;
1123
1124     case BRC_GENL_C_GET_PORTS:
1125         handle_get_ports_cmd(ovs, buffer);
1126         break;
1127
1128     default:
1129         VLOG_WARN_RL(&rl, "received unknown brc netlink command: %d\n",
1130                      genlmsghdr->cmd);
1131         break;
1132     }
1133
1134 error:
1135     ofpbuf_delete(buffer);
1136     return;
1137 }
1138
1139 static void
1140 netdev_changed_cb(const struct rtnetlink_link_change *change, void *idl_)
1141 {
1142     struct ovsdb_idl *idl = idl_;
1143     const struct ovsrec_open_vswitch *ovs;
1144     const struct ovsrec_interface *iface;
1145     struct ovsdb_idl_txn *txn;
1146     struct ovsrec_port *port;
1147     struct ovsrec_bridge *br;
1148     char br_name[IFNAMSIZ];
1149     const char *port_name;
1150
1151     if (!change) {
1152         VLOG_WARN_RL(&rl, "network monitor socket overflowed");
1153         return;
1154     }
1155
1156     if (change->nlmsg_type != RTM_DELLINK || !change->master_ifindex) {
1157         return;
1158     }
1159
1160     ovs = ovsrec_open_vswitch_first(idl);
1161     if (!ovs) {
1162         return;
1163     }
1164
1165     port_name = change->ifname;
1166     if (!if_indextoname(change->master_ifindex, br_name)) {
1167         return;
1168     }
1169
1170     if (netdev_exists(port_name)) {
1171         /* A network device by that name exists even though the kernel
1172          * told us it had disappeared.  Probably, what happened was
1173          * this:
1174          *
1175          *      1. Device destroyed.
1176          *      2. Notification sent to us.
1177          *      3. New device created with same name as old one.
1178          *      4. ovs-brcompatd notified, removes device from bridge.
1179          *
1180          * There's no a priori reason that in this situation that the
1181          * new device with the same name should remain in the bridge;
1182          * on the contrary, that would be unexpected.  *But* there is
1183          * one important situation where, if we do this, bad things
1184          * happen.  This is the case of XenServer Tools version 5.0.0,
1185          * which on boot of a Windows VM cause something like this to
1186          * happen on the Xen host:
1187          *
1188          *      i. Create tap1.0 and vif1.0.
1189          *      ii. Delete tap1.0.
1190          *      iii. Delete vif1.0.
1191          *      iv. Re-create vif1.0.
1192          *
1193          * (XenServer Tools 5.5.0 does not exhibit this behavior, and
1194          * neither does a VM without Tools installed at all.)
1195          *
1196          * Steps iii and iv happen within a few seconds of each other.
1197          * Step iv causes /etc/xensource/scripts/vif to run, which in
1198          * turn calls ovs-cfg-mod to add the new device to the bridge.
1199          * If step iv happens after step 4 (in our first list of
1200          * steps), then all is well, but if it happens between 3 and 4
1201          * (which can easily happen if ovs-brcompatd has to wait to
1202          * lock the configuration file), then we will remove the new
1203          * incarnation from the bridge instead of the old one!
1204          *
1205          * So, to avoid this problem, we do nothing here.  This is
1206          * strictly incorrect except for this one particular case, and
1207          * perhaps that will bite us someday.  If that happens, then we
1208          * will have to somehow track network devices by ifindex, since
1209          * a new device will have a new ifindex even if it has the same
1210          * name as an old device.
1211          */
1212         VLOG_INFO("kernel reported network device %s removed but "
1213                   "a device by that name exists (XS Tools 5.0.0?)",
1214                   port_name);
1215         return;
1216     }
1217
1218     VLOG_INFO("network device %s destroyed, removing from bridge %s",
1219               port_name, br_name);
1220
1221     br = find_bridge(ovs, br_name);
1222     if (!br) {
1223         VLOG_WARN("no bridge named %s from which to remove %s",
1224                   br_name, port_name);
1225         return;
1226     }
1227
1228     iface = find_interface(br, port_name, &port);
1229     if (!iface) {
1230         return;
1231     }
1232
1233     txn = ovsdb_idl_txn_create(idl);
1234     del_interface(br, port, iface);
1235     ovsdb_idl_txn_add_comment(txn, "ovs-brcompatd: destroy port %s",
1236                               port_name);
1237     commit_txn(txn, false);
1238 }
1239
1240 int
1241 main(int argc, char *argv[])
1242 {
1243     extern struct vlog_module VLM_reconnect;
1244     struct rtnetlink_notifier link_notifier;
1245     struct unixctl_server *unixctl;
1246     const char *remote;
1247     struct ovsdb_idl *idl;
1248     int retval;
1249
1250     proctitle_init(argc, argv);
1251     set_program_name(argv[0]);
1252     vlog_set_levels(NULL, VLF_CONSOLE, VLL_WARN);
1253     vlog_set_levels(&VLM_reconnect, VLF_ANY_FACILITY, VLL_WARN);
1254
1255     remote = parse_options(argc, argv);
1256     signal(SIGPIPE, SIG_IGN);
1257     process_init();
1258     ovsrec_init();
1259
1260     daemonize_start();
1261
1262     retval = unixctl_server_create(NULL, &unixctl);
1263     if (retval) {
1264         exit(EXIT_FAILURE);
1265     }
1266
1267     if (brc_open(&brc_sock)) {
1268         VLOG_FATAL("could not open brcompat socket.  Check "
1269                    "\"brcompat\" kernel module.");
1270     }
1271
1272
1273     rtnetlink_link_notifier_register(&link_notifier, netdev_changed_cb, NULL);
1274
1275     daemonize_complete();
1276
1277     idl = ovsdb_idl_create(remote, &ovsrec_idl_class, true);
1278
1279     for (;;) {
1280         const struct ovsrec_open_vswitch *ovs;
1281
1282         ovsdb_idl_run(idl);
1283
1284         unixctl_server_run(unixctl);
1285         rtnetlink_link_notifier_run();
1286         brc_recv_update(idl);
1287
1288         ovs = ovsrec_open_vswitch_first(idl);
1289         if (!ovs && ovsdb_idl_has_ever_connected(idl)) {
1290             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 1);
1291             VLOG_WARN_RL(&rl, "%s: database does not contain any Open vSwitch "
1292                          "configuration", remote);
1293         }
1294         netdev_run();
1295
1296         nl_sock_wait(brc_sock, POLLIN);
1297         ovsdb_idl_wait(idl);
1298         unixctl_server_wait(unixctl);
1299         rtnetlink_link_notifier_wait();
1300         netdev_wait();
1301         poll_block();
1302     }
1303
1304     rtnetlink_link_notifier_unregister(&link_notifier);
1305     ovsdb_idl_destroy(idl);
1306
1307     return 0;
1308 }
1309
1310 static void
1311 validate_appctl_command(void)
1312 {
1313     const char *p;
1314     int n;
1315
1316     n = 0;
1317     for (p = strchr(appctl_command, '%'); p; p = strchr(p + 2, '%')) {
1318         if (p[1] == '%') {
1319             /* Nothing to do. */
1320         } else if (p[1] == 's') {
1321             n++;
1322         } else {
1323             VLOG_FATAL("only '%%s' and '%%%%' allowed in --appctl-command");
1324         }
1325     }
1326     if (n != 1) {
1327         VLOG_FATAL("'%%s' must appear exactly once in --appctl-command");
1328     }
1329 }
1330
1331 static const char *
1332 parse_options(int argc, char *argv[])
1333 {
1334     enum {
1335         OPT_APPCTL_COMMAND,
1336         VLOG_OPTION_ENUMS,
1337         LEAK_CHECKER_OPTION_ENUMS,
1338         DAEMON_OPTION_ENUMS
1339     };
1340     static struct option long_options[] = {
1341         {"help",             no_argument, NULL, 'h'},
1342         {"version",          no_argument, NULL, 'V'},
1343         {"appctl-command",   required_argument, NULL, OPT_APPCTL_COMMAND},
1344         DAEMON_LONG_OPTIONS,
1345         VLOG_LONG_OPTIONS,
1346         LEAK_CHECKER_LONG_OPTIONS,
1347         {NULL, 0, NULL, 0},
1348     };
1349     char *short_options = long_options_to_short_options(long_options);
1350
1351     appctl_command = xasprintf("%s/ovs-appctl %%s", ovs_bindir());
1352     for (;;) {
1353         int c;
1354
1355         c = getopt_long(argc, argv, short_options, long_options, NULL);
1356         if (c == -1) {
1357             break;
1358         }
1359
1360         switch (c) {
1361         case 'H':
1362         case 'h':
1363             usage();
1364
1365         case 'V':
1366             OVS_PRINT_VERSION(0, 0);
1367             exit(EXIT_SUCCESS);
1368
1369         case OPT_APPCTL_COMMAND:
1370             appctl_command = optarg;
1371             break;
1372
1373         VLOG_OPTION_HANDLERS
1374         DAEMON_OPTION_HANDLERS
1375         LEAK_CHECKER_OPTION_HANDLERS
1376
1377         case '?':
1378             exit(EXIT_FAILURE);
1379
1380         default:
1381             abort();
1382         }
1383     }
1384     free(short_options);
1385
1386     validate_appctl_command();
1387
1388     argc -= optind;
1389     argv += optind;
1390
1391     if (argc != 1) {
1392         VLOG_FATAL("database socket is non-option argument; "
1393                    "use --help for usage");
1394     }
1395
1396     return argv[0];
1397 }
1398
1399 static void
1400 usage(void)
1401 {
1402     printf("%s: bridge compatibility front-end for ovs-vswitchd\n"
1403            "usage: %s [OPTIONS] CONFIG\n"
1404            "CONFIG is the configuration file used by ovs-vswitchd.\n",
1405            program_name, program_name);
1406     printf("\nConfiguration options:\n"
1407            "  --appctl-command=COMMAND  shell command to run ovs-appctl\n"
1408           );
1409     daemon_usage();
1410     vlog_usage();
1411     printf("\nOther options:\n"
1412            "  -h, --help              display this help message\n"
1413            "  -V, --version           display version information\n");
1414     leak_checker_usage();
1415     printf("\nThe default appctl command is:\n%s\n", appctl_command);
1416     exit(EXIT_SUCCESS);
1417 }