Merge citrix branch into master.
[sliver-openvswitch.git] / vswitchd / ovs-brcompatd.c
1 /* Copyright (c) 2008, 2009 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 "cfg.h"
37 #include "command-line.h"
38 #include "coverage.h"
39 #include "daemon.h"
40 #include "dirs.h"
41 #include "dynamic-string.h"
42 #include "fatal-signal.h"
43 #include "fault.h"
44 #include "leak-checker.h"
45 #include "netdev.h"
46 #include "netlink.h"
47 #include "ofpbuf.h"
48 #include "openvswitch/brcompat-netlink.h"
49 #include "packets.h"
50 #include "poll-loop.h"
51 #include "process.h"
52 #include "signals.h"
53 #include "svec.h"
54 #include "timeval.h"
55 #include "unixctl.h"
56 #include "util.h"
57
58 #include "vlog.h"
59 #define THIS_MODULE VLM_brcompatd
60
61
62 /* xxx Just hangs if datapath is rmmod/insmod.  Learn to reconnect? */
63
64 /* Actions to modify bridge compatibility configuration. */
65 enum bmc_action {
66     BMC_ADD_DP,
67     BMC_DEL_DP,
68     BMC_ADD_PORT,
69     BMC_DEL_PORT
70 };
71
72 static void parse_options(int argc, char *argv[]);
73 static void usage(void) NO_RETURN;
74
75 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 60);
76
77 /* Maximum number of milliseconds to wait for the config file to be
78  * unlocked.  If set to zero, no waiting will occur. */
79 static int lock_timeout = 500;
80
81 /* Maximum number of milliseconds to wait before pruning port entries that 
82  * no longer exist.  If set to zero, ports are never pruned. */
83 static int prune_timeout = 5000;
84
85 /* Config file shared with ovs-vswitchd (usually ovs-vswitchd.conf). */
86 static char *config_file;
87
88 /* Shell command to execute (via popen()) to send a control command to the
89  * running ovs-vswitchd process.  The string must contain one instance of %s,
90  * which is replaced by the control command. */
91 static char *appctl_command;
92
93 /* Netlink socket to listen for interface changes. */
94 static struct nl_sock *rtnl_sock;
95
96 /* Netlink socket to bridge compatibility kernel module. */
97 static struct nl_sock *brc_sock;
98
99 /* The Generic Netlink family number used for bridge compatibility. */
100 static int brc_family;
101
102 static const struct nl_policy brc_multicast_policy[] = {
103     [BRC_GENL_A_MC_GROUP] = {.type = NL_A_U32 }
104 };
105
106 static const struct nl_policy rtnlgrp_link_policy[] = {
107     [IFLA_IFNAME] = { .type = NL_A_STRING, .optional = false },
108     [IFLA_MASTER] = { .type = NL_A_U32, .optional = true },
109 };
110
111 static int
112 lookup_brc_multicast_group(int *multicast_group)
113 {
114     struct nl_sock *sock;
115     struct ofpbuf request, *reply;
116     struct nlattr *attrs[ARRAY_SIZE(brc_multicast_policy)];
117     int retval;
118
119     retval = nl_sock_create(NETLINK_GENERIC, 0, 0, 0, &sock);
120     if (retval) {
121         return retval;
122     }
123     ofpbuf_init(&request, 0);
124     nl_msg_put_genlmsghdr(&request, sock, 0, brc_family,
125             NLM_F_REQUEST, BRC_GENL_C_QUERY_MC, 1);
126     retval = nl_sock_transact(sock, &request, &reply);
127     ofpbuf_uninit(&request);
128     if (retval) {
129         nl_sock_destroy(sock);
130         return retval;
131     }
132     if (!nl_policy_parse(reply, NLMSG_HDRLEN + GENL_HDRLEN,
133                          brc_multicast_policy, attrs,
134                          ARRAY_SIZE(brc_multicast_policy))) {
135         nl_sock_destroy(sock);
136         ofpbuf_delete(reply);
137         return EPROTO;
138     }
139     *multicast_group = nl_attr_get_u32(attrs[BRC_GENL_A_MC_GROUP]);
140     nl_sock_destroy(sock);
141     ofpbuf_delete(reply);
142
143     return 0;
144 }
145
146 /* Opens a socket for brcompat notifications.  Returns 0 if successful,
147  * otherwise a positive errno value. */
148 static int
149 brc_open(struct nl_sock **sock)
150 {
151     int multicast_group = 0;
152     int retval;
153
154     retval = nl_lookup_genl_family(BRC_GENL_FAMILY_NAME, &brc_family);
155     if (retval) {
156         return retval;
157     }
158
159     retval = lookup_brc_multicast_group(&multicast_group);
160     if (retval) {
161         return retval;
162     }
163
164     retval = nl_sock_create(NETLINK_GENERIC, multicast_group, 0, 0, sock);
165     if (retval) {
166         return retval;
167     }
168
169     return 0;
170 }
171
172 static const struct nl_policy brc_dp_policy[] = {
173     [BRC_GENL_A_DP_NAME] = { .type = NL_A_STRING },
174 };
175
176 static bool
177 bridge_exists(const char *name)
178 {
179     return cfg_has_section("bridge.%s", name);
180 }
181
182 static int
183 execute_appctl_command(const char *unixctl_command, char **output)
184 {
185     char *stdout_log, *stderr_log;
186     int error, status;
187     char *argv[5];
188
189     argv[0] = "/bin/sh";
190     argv[1] = "-c";
191     argv[2] = xasprintf(appctl_command, unixctl_command);
192     argv[3] = NULL;
193
194     /* Run process and log status. */
195     error = process_run_capture(argv, &stdout_log, &stderr_log, &status);
196     if (error) {
197         VLOG_ERR("failed to execute %s command via ovs-appctl: %s",
198                  unixctl_command, strerror(error));
199     } else if (status) {
200         char *msg = process_status_msg(status);
201         VLOG_ERR("ovs-appctl exited with error (%s)", msg);
202         free(msg);
203         error = ECHILD;
204     }
205
206     /* Deal with stdout_log. */
207     if (output) {
208         *output = stdout_log;
209     } else {
210         free(stdout_log);
211     }
212
213     /* Deal with stderr_log */
214     if (stderr_log && *stderr_log) {
215         VLOG_INFO("ovs-appctl wrote to stderr:\n%s", stderr_log);
216     }
217     free(stderr_log);
218
219     free(argv[2]);
220
221     return error;
222 }
223
224 static int
225 rewrite_and_reload_config(void)
226 {
227     if (cfg_is_dirty()) {
228         int error1 = cfg_write();
229         int error2 = cfg_read();
230         long long int reload_start = time_msec();
231         int error3 = execute_appctl_command("vswitchd/reload", NULL);
232         long long int elapsed = time_msec() - reload_start;
233         COVERAGE_INC(brcompatd_reload);
234         if (elapsed > 0) {
235             VLOG_INFO("reload command executed in %lld ms", elapsed);
236         }
237         return error1 ? error1 : error2 ? error2 : error3;
238     }
239     return 0;
240 }
241
242 static void
243 do_get_bridge_parts(const char *bridge, struct svec *parts, int vlan,
244                     bool break_down_bonds)
245 {
246     struct svec ports;
247     int i;
248
249     svec_init(&ports);
250     cfg_get_all_keys(&ports, "bridge.%s.port", bridge);
251     for (i = 0; i < ports.n; i++) {
252         const char *port_name = ports.names[i];
253         if (vlan >= 0) {
254             int port_vlan = cfg_get_vlan(0, "vlan.%s.tag", port_name);
255             if (port_vlan < 0) {
256                 port_vlan = 0;
257             }
258             if (vlan != port_vlan) {
259                 continue;
260             }
261         }
262         if (break_down_bonds && cfg_has_section("bonding.%s", port_name)) {
263             struct svec slaves;
264             svec_init(&slaves);
265             cfg_get_all_keys(&slaves, "bonding.%s.slave", port_name);
266             svec_append(parts, &slaves);
267             svec_destroy(&slaves);
268         } else {
269             svec_add(parts, port_name);
270         }
271     }
272     svec_destroy(&ports);
273 }
274
275 /* Add all the interfaces for 'bridge' to 'ifaces', breaking bonded interfaces
276  * down into their constituent parts.
277  *
278  * If 'vlan' < 0, all interfaces on 'bridge' are reported.  If 'vlan' == 0,
279  * then only interfaces for trunk ports or ports with implicit VLAN 0 are
280  * reported.  If 'vlan' > 0, only interfaces with implicit VLAN 'vlan' are
281  * reported.  */
282 static void
283 get_bridge_ifaces(const char *bridge, struct svec *ifaces, int vlan)
284 {
285     do_get_bridge_parts(bridge, ifaces, vlan, true);
286 }
287
288 /* Add all the ports for 'bridge' to 'ports'.  Bonded ports are reported under
289  * the bond name, not broken down into their constituent interfaces.
290  *
291  * If 'vlan' < 0, all ports on 'bridge' are reported.  If 'vlan' == 0, then
292  * only trunk ports or ports with implicit VLAN 0 are reported.  If 'vlan' > 0,
293  * only port with implicit VLAN 'vlan' are reported.  */
294 static void
295 get_bridge_ports(const char *bridge, struct svec *ports, int vlan)
296 {
297     do_get_bridge_parts(bridge, ports, vlan, false);
298 }
299
300 /* Go through the configuration file and remove any ports that no longer
301  * exist associated with a bridge. */
302 static void
303 prune_ports(void)
304 {
305     int i, j;
306     struct svec bridges, delete;
307
308     if (cfg_lock(NULL, 0)) {
309         /* Couldn't lock config file. */
310         return;
311     }
312
313     svec_init(&bridges);
314     svec_init(&delete);
315     cfg_get_subsections(&bridges, "bridge");
316     for (i=0; i<bridges.n; i++) {
317         const char *br_name = bridges.names[i];
318         struct svec ifaces;
319
320         /* Check that each bridge interface exists. */
321         svec_init(&ifaces);
322         get_bridge_ifaces(br_name, &ifaces, -1);
323         for (j = 0; j < ifaces.n; j++) {
324             const char *iface_name = ifaces.names[j];
325
326             /* The local port and internal ports are created and destroyed by
327              * ovs-vswitchd itself, so don't bother checking for them at all.
328              * In practice, they might not exist if ovs-vswitchd hasn't
329              * finished reloading since the configuration file was updated. */
330             if (!strcmp(iface_name, br_name)
331                 || cfg_get_bool(0, "iface.%s.internal", iface_name)) {
332                 continue;
333             }
334
335             if (!netdev_exists(iface_name)) {
336                 VLOG_INFO_RL(&rl, "removing dead interface %s from %s",
337                              iface_name, br_name);
338                 svec_add(&delete, iface_name);
339             }
340         }
341         svec_destroy(&ifaces);
342     }
343     svec_destroy(&bridges);
344
345     if (delete.n) {
346         size_t i;
347
348         for (i = 0; i < delete.n; i++) {
349             cfg_del_match("bridge.*.port=%s", delete.names[i]);
350             cfg_del_match("bonding.*.slave=%s", delete.names[i]);
351         }
352         rewrite_and_reload_config();
353         cfg_unlock();
354     } else {
355         cfg_unlock();
356     }
357     svec_destroy(&delete);
358 }
359
360 static int
361 add_bridge(const char *br_name)
362 {
363     if (bridge_exists(br_name)) {
364         VLOG_WARN("addbr %s: bridge %s exists", br_name, br_name);
365         return EEXIST;
366     } else if (netdev_exists(br_name)) {
367         if (cfg_get_bool(0, "iface.%s.fake-bridge", br_name)) {
368             VLOG_WARN("addbr %s: %s exists as a fake bridge",
369                       br_name, br_name);
370             return 0;
371         } else {
372             VLOG_WARN("addbr %s: cannot create bridge %s because a network "
373                       "device named %s already exists",
374                       br_name, br_name, br_name);
375             return EEXIST;
376         }
377     }
378
379     cfg_add_entry("bridge.%s.port=%s", br_name, br_name);
380     VLOG_INFO("addbr %s: success", br_name);
381
382     return 0;
383 }
384
385 static int 
386 del_bridge(const char *br_name)
387 {
388     if (!bridge_exists(br_name)) {
389         VLOG_WARN("delbr %s: no bridge named %s", br_name, br_name);
390         return ENXIO;
391     }
392
393     cfg_del_section("bridge.%s", br_name);
394     VLOG_INFO("delbr %s: success", br_name);
395
396     return 0;
397 }
398
399 static int
400 parse_command(struct ofpbuf *buffer, uint32_t *seq, const char **br_name,
401               const char **port_name, uint64_t *count, uint64_t *skip)
402 {
403     static const struct nl_policy policy[] = {
404         [BRC_GENL_A_DP_NAME] = { .type = NL_A_STRING, .optional = true },
405         [BRC_GENL_A_PORT_NAME] = { .type = NL_A_STRING, .optional = true },
406         [BRC_GENL_A_FDB_COUNT] = { .type = NL_A_U64, .optional = true },
407         [BRC_GENL_A_FDB_SKIP] = { .type = NL_A_U64, .optional = true },
408     };
409     struct nlattr *attrs[ARRAY_SIZE(policy)];
410
411     if (!nl_policy_parse(buffer, NLMSG_HDRLEN + GENL_HDRLEN, policy,
412                          attrs, ARRAY_SIZE(policy))
413         || (br_name && !attrs[BRC_GENL_A_DP_NAME])
414         || (port_name && !attrs[BRC_GENL_A_PORT_NAME])
415         || (count && !attrs[BRC_GENL_A_FDB_COUNT])
416         || (skip && !attrs[BRC_GENL_A_FDB_SKIP])) {
417         return EINVAL;
418     }
419
420     *seq = ((struct nlmsghdr *) buffer->data)->nlmsg_seq;
421     if (br_name) {
422         *br_name = nl_attr_get_string(attrs[BRC_GENL_A_DP_NAME]);
423     }
424     if (port_name) {
425         *port_name = nl_attr_get_string(attrs[BRC_GENL_A_PORT_NAME]);
426     }
427     if (count) {
428         *count = nl_attr_get_u64(attrs[BRC_GENL_A_FDB_COUNT]);
429     }
430     if (skip) {
431         *skip = nl_attr_get_u64(attrs[BRC_GENL_A_FDB_SKIP]);
432     }
433     return 0;
434 }
435
436 /* Composes and returns a reply to a request made by the datapath with Netlink
437  * sequence number 'seq' and error code 'error'.  The caller may add additional
438  * attributes to the message, then it may send it with send_reply(). */
439 static struct ofpbuf *
440 compose_reply(uint32_t seq, int error)
441 {
442     struct ofpbuf *reply = ofpbuf_new(4096);
443     nl_msg_put_genlmsghdr(reply, brc_sock, 32, brc_family, NLM_F_REQUEST,
444                           BRC_GENL_C_DP_RESULT, 1);
445     ((struct nlmsghdr *) reply->data)->nlmsg_seq = seq;
446     nl_msg_put_u32(reply, BRC_GENL_A_ERR_CODE, error);
447     return reply;
448 }
449
450 /* Sends 'reply' to the datapath and frees it. */
451 static void
452 send_reply(struct ofpbuf *reply)
453 {
454     int retval = nl_sock_send(brc_sock, reply, false);
455     if (retval) {
456         VLOG_WARN_RL(&rl, "replying to brcompat request: %s",
457                      strerror(retval));
458     }
459     ofpbuf_delete(reply);
460 }
461
462 /* Composes and sends a reply to a request made by the datapath with Netlink
463  * sequence number 'seq' and error code 'error'. */
464 static void
465 send_simple_reply(uint32_t seq, int error)
466 {
467     send_reply(compose_reply(seq, error));
468 }
469
470 static int
471 handle_bridge_cmd(struct ofpbuf *buffer, bool add)
472 {
473     const char *br_name;
474     uint32_t seq;
475     int error;
476
477     error = parse_command(buffer, &seq, &br_name, NULL, NULL, NULL);
478     if (!error) {
479         error = add ? add_bridge(br_name) : del_bridge(br_name);
480         if (!error) {
481             error = rewrite_and_reload_config();
482         }
483         send_simple_reply(seq, error);
484     }
485     return error;
486 }
487
488 static const struct nl_policy brc_port_policy[] = {
489     [BRC_GENL_A_DP_NAME] = { .type = NL_A_STRING },
490     [BRC_GENL_A_PORT_NAME] = { .type = NL_A_STRING },
491 };
492
493 static void
494 del_port(const char *br_name, const char *port_name)
495 {
496     cfg_del_entry("bridge.%s.port=%s", br_name, port_name);
497     cfg_del_match("bonding.*.slave=%s", port_name);
498     cfg_del_match("vlan.%s.[!0-9]*", port_name);
499 }
500
501 static int
502 handle_port_cmd(struct ofpbuf *buffer, bool add)
503 {
504     const char *cmd_name = add ? "add-if" : "del-if";
505     const char *br_name, *port_name;
506     uint32_t seq;
507     int error;
508
509     error = parse_command(buffer, &seq, &br_name, &port_name, NULL, NULL);
510     if (!error) {
511         if (!bridge_exists(br_name)) {
512             VLOG_WARN("%s %s %s: no bridge named %s",
513                       cmd_name, br_name, port_name, br_name);
514             error = EINVAL;
515         } else if (!netdev_exists(port_name)) {
516             VLOG_WARN("%s %s %s: no network device named %s",
517                       cmd_name, br_name, port_name, port_name);
518             error = EINVAL;
519         } else {
520             if (add) {
521                 cfg_add_entry("bridge.%s.port=%s", br_name, port_name);
522             } else {
523                 del_port(br_name, port_name);
524             }
525             VLOG_INFO("%s %s %s: success", cmd_name, br_name, port_name);
526             error = rewrite_and_reload_config();
527         }
528         send_simple_reply(seq, error);
529     }
530
531     return error;
532 }
533
534 /* Returns the name of the bridge that contains a port named 'port_name', as a
535  * malloc'd string that the caller must free, or a null pointer if no bridge
536  * contains a port named 'port_name'. */
537 static char *
538 get_bridge_containing_port(const char *port_name)
539 {
540     struct svec matches;
541     const char *start, *end;
542
543     svec_init(&matches);
544     cfg_get_matches(&matches, "bridge.*.port=%s", port_name);
545     if (!matches.n) {
546         return 0;
547     }
548
549     start = matches.names[0] + strlen("bridge.");
550     end = strstr(start, ".port=");
551     assert(end);
552     return xmemdup0(start, end - start);
553 }
554
555 static int
556 linux_bridge_to_ovs_bridge(const char *linux_bridge,
557                            char **ovs_bridge, int *br_vlan)
558 {
559     if (bridge_exists(linux_bridge)) {
560         /* Bridge name is the same.  We are interested in VLAN 0. */
561         *ovs_bridge = xstrdup(linux_bridge);
562         *br_vlan = 0;
563         return 0;
564     } else {
565         /* No such Open vSwitch bridge 'linux_bridge', but there might be an
566          * internal port named 'linux_bridge' on some other bridge
567          * 'ovs_bridge'.  If so then we are interested in the VLAN assigned to
568          * port 'linux_bridge' on the bridge named 'ovs_bridge'. */
569         const char *port_name = linux_bridge;
570
571         *ovs_bridge = get_bridge_containing_port(port_name);
572         *br_vlan = cfg_get_vlan(0, "vlan.%s.tag", port_name);
573         if (*ovs_bridge && *br_vlan >= 0) {
574             return 0;
575         } else {
576             free(*ovs_bridge);
577             return ENODEV;
578         }
579     }
580 }
581
582 static int
583 handle_fdb_query_cmd(struct ofpbuf *buffer)
584 {
585     /* This structure is copied directly from the Linux 2.6.30 header files.
586      * It would be more straightforward to #include <linux/if_bridge.h>, but
587      * the 'port_hi' member was only introduced in Linux 2.6.26 and so systems
588      * with old header files won't have it. */
589     struct __fdb_entry {
590         __u8 mac_addr[6];
591         __u8 port_no;
592         __u8 is_local;
593         __u32 ageing_timer_value;
594         __u8 port_hi;
595         __u8 pad0;
596         __u16 unused;
597     };
598
599     struct mac {
600         uint8_t addr[6];
601     };
602     struct mac *local_macs;
603     int n_local_macs;
604     int i;
605
606     /* Impedance matching between the vswitchd and Linux kernel notions of what
607      * a bridge is.  The kernel only handles a single VLAN per bridge, but
608      * vswitchd can deal with all the VLANs on a single bridge.  We have to
609      * pretend that the former is the case even though the latter is the
610      * implementation. */
611     const char *linux_bridge;   /* Name used by brctl. */
612     char *ovs_bridge;           /* Name used by ovs-vswitchd. */
613     int br_vlan;                /* VLAN tag. */
614     struct svec ifaces;
615
616     struct ofpbuf query_data;
617     struct ofpbuf *reply;
618     char *unixctl_command;
619     uint64_t count, skip;
620     char *output;
621     char *save_ptr;
622     uint32_t seq;
623     int error;
624
625     /* Parse the command received from brcompat_mod. */
626     error = parse_command(buffer, &seq, &linux_bridge, NULL, &count, &skip);
627     if (error) {
628         return error;
629     }
630
631     /* Figure out vswitchd bridge and VLAN. */
632     cfg_read();
633     error = linux_bridge_to_ovs_bridge(linux_bridge, &ovs_bridge, &br_vlan);
634     if (error) {
635         send_simple_reply(seq, error);
636         return error;
637     }
638
639     /* Fetch the forwarding database using ovs-appctl. */
640     unixctl_command = xasprintf("fdb/show %s", ovs_bridge);
641     error = execute_appctl_command(unixctl_command, &output);
642     free(unixctl_command);
643     if (error) {
644         free(ovs_bridge);
645         send_simple_reply(seq, error);
646         return error;
647     }
648
649     /* Fetch the MAC address for each interface on the bridge, so that we can
650      * fill in the is_local field in the response. */
651     svec_init(&ifaces);
652     get_bridge_ifaces(ovs_bridge, &ifaces, br_vlan);
653     local_macs = xmalloc(ifaces.n * sizeof *local_macs);
654     n_local_macs = 0;
655     for (i = 0; i < ifaces.n; i++) {
656         const char *iface_name = ifaces.names[i];
657         struct mac *mac = &local_macs[n_local_macs];
658         struct netdev *netdev;
659
660         error = netdev_open(iface_name, NETDEV_ETH_TYPE_NONE, &netdev);
661         if (netdev) {
662             if (!netdev_get_etheraddr(netdev, mac->addr)) {
663                 n_local_macs++;
664             }
665             netdev_close(netdev);
666         }
667     }
668     svec_destroy(&ifaces);
669
670     /* Parse the response from ovs-appctl and convert it to binary format to
671      * pass back to the kernel. */
672     ofpbuf_init(&query_data, sizeof(struct __fdb_entry) * 8);
673     save_ptr = NULL;
674     strtok_r(output, "\n", &save_ptr); /* Skip header line. */
675     while (count > 0) {
676         struct __fdb_entry *entry;
677         int port, vlan, age;
678         uint8_t mac[ETH_ADDR_LEN];
679         char *line;
680         bool is_local;
681
682         line = strtok_r(NULL, "\n", &save_ptr);
683         if (!line) {
684             break;
685         }
686
687         if (sscanf(line, "%d %d "ETH_ADDR_SCAN_FMT" %d",
688                    &port, &vlan, ETH_ADDR_SCAN_ARGS(mac), &age)
689             != 2 + ETH_ADDR_SCAN_COUNT + 1) {
690             struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 1);
691             VLOG_INFO_RL(&rl, "fdb/show output has invalid format: %s", line);
692             continue;
693         }
694
695         if (vlan != br_vlan) {
696             continue;
697         }
698
699         if (skip > 0) {
700             skip--;
701             continue;
702         }
703
704         /* Is this the MAC address of an interface on the bridge? */
705         is_local = false;
706         for (i = 0; i < n_local_macs; i++) {
707             if (eth_addr_equals(local_macs[i].addr, mac)) {
708                 is_local = true;
709                 break;
710             }
711         }
712
713         entry = ofpbuf_put_uninit(&query_data, sizeof *entry);
714         memcpy(entry->mac_addr, mac, ETH_ADDR_LEN);
715         entry->port_no = port & 0xff;
716         entry->is_local = is_local;
717         entry->ageing_timer_value = age * HZ;
718         entry->port_hi = (port & 0xff00) >> 8;
719         entry->pad0 = 0;
720         entry->unused = 0;
721         count--;
722     }
723     free(output);
724
725     /* Compose and send reply to datapath. */
726     reply = compose_reply(seq, 0);
727     nl_msg_put_unspec(reply, BRC_GENL_A_FDB_DATA,
728                       query_data.data, query_data.size);
729     send_reply(reply);
730
731     /* Free memory. */
732     ofpbuf_uninit(&query_data);
733     free(ovs_bridge);
734
735     return 0;
736 }
737
738 static void
739 send_ifindex_reply(uint32_t seq, struct svec *ifaces)
740 {
741     struct ofpbuf *reply;
742     const char *iface;
743     size_t n_indices;
744     int *indices;
745     size_t i;
746
747     /* Make sure that any given interface only occurs once.  This shouldn't
748      * happen, but who knows what people put into their configuration files. */
749     svec_sort_unique(ifaces);
750
751     /* Convert 'ifaces' into ifindexes. */
752     n_indices = 0;
753     indices = xmalloc(ifaces->n * sizeof *indices);
754     SVEC_FOR_EACH (i, iface, ifaces) {
755         int ifindex = if_nametoindex(iface);
756         if (ifindex) {
757             indices[n_indices++] = ifindex;
758         }
759     }
760
761     /* Compose and send reply. */
762     reply = compose_reply(seq, 0);
763     nl_msg_put_unspec(reply, BRC_GENL_A_IFINDEXES,
764                       indices, n_indices * sizeof *indices);
765     send_reply(reply);
766
767     /* Free memory. */
768     free(indices);
769 }
770
771 static int
772 handle_get_bridges_cmd(struct ofpbuf *buffer)
773 {
774     struct svec bridges;
775     const char *br_name;
776     size_t i;
777
778     uint32_t seq;
779
780     int error;
781
782     /* Parse Netlink command.
783      *
784      * The command doesn't actually have any arguments, but we need the
785      * sequence number to send the reply. */
786     error = parse_command(buffer, &seq, NULL, NULL, NULL, NULL);
787     if (error) {
788         return error;
789     }
790
791     /* Get all the real bridges and all the fake ones. */
792     cfg_read();
793     svec_init(&bridges);
794     cfg_get_subsections(&bridges, "bridge");
795     SVEC_FOR_EACH (i, br_name, &bridges) {
796         const char *iface_name;
797         struct svec ifaces;
798         size_t j;
799
800         svec_init(&ifaces);
801         get_bridge_ifaces(br_name, &ifaces, -1);
802         SVEC_FOR_EACH (j, iface_name, &ifaces) {
803             if (cfg_get_bool(0, "iface.%s.fake-bridge", iface_name)) {
804                 svec_add(&bridges, iface_name);
805             }
806         }
807         svec_destroy(&ifaces);
808     }
809
810     send_ifindex_reply(seq, &bridges);
811     svec_destroy(&bridges);
812
813     return 0;
814 }
815
816 static int
817 handle_get_ports_cmd(struct ofpbuf *buffer)
818 {
819     uint32_t seq;
820
821     const char *linux_bridge;
822     char *ovs_bridge;
823     int br_vlan;
824
825     struct svec ports;
826
827     int error;
828
829     /* Parse Netlink command. */
830     error = parse_command(buffer, &seq, &linux_bridge, NULL, NULL, NULL);
831     if (error) {
832         return error;
833     }
834
835     cfg_read();
836     error = linux_bridge_to_ovs_bridge(linux_bridge, &ovs_bridge, &br_vlan);
837     if (error) {
838         send_simple_reply(seq, error);
839         return error;
840     }
841
842     svec_init(&ports);
843     get_bridge_ports(ovs_bridge, &ports, br_vlan);
844     svec_sort(&ports);
845     svec_del(&ports, linux_bridge);
846     send_ifindex_reply(seq, &ports); /* XXX bonds won't show up */
847     svec_destroy(&ports);
848
849     free(ovs_bridge);
850
851     return 0;
852 }
853
854 static int
855 brc_recv_update(void)
856 {
857     int retval;
858     struct ofpbuf *buffer;
859     struct genlmsghdr *genlmsghdr;
860
861
862     buffer = NULL;
863     do {
864         ofpbuf_delete(buffer);
865         retval = nl_sock_recv(brc_sock, &buffer, false);
866     } while (retval == ENOBUFS
867             || (!retval
868                 && (nl_msg_nlmsgerr(buffer, NULL)
869                     || nl_msg_nlmsghdr(buffer)->nlmsg_type == NLMSG_DONE)));
870     if (retval) {
871         if (retval != EAGAIN) {
872             VLOG_WARN_RL(&rl, "brc_recv_update: %s", strerror(retval));
873         }
874         return retval;
875     }
876
877     genlmsghdr = nl_msg_genlmsghdr(buffer);
878     if (!genlmsghdr) {
879         VLOG_WARN_RL(&rl, "received packet too short for generic NetLink");
880         goto error;
881     }
882
883     if (nl_msg_nlmsghdr(buffer)->nlmsg_type != brc_family) {
884         VLOG_DBG_RL(&rl, "received type (%"PRIu16") != brcompat family (%d)",
885                 nl_msg_nlmsghdr(buffer)->nlmsg_type, brc_family);
886         goto error;
887     }
888
889     if (cfg_lock(NULL, lock_timeout)) {
890         /* Couldn't lock config file. */
891         retval = EAGAIN;
892         goto error;
893     }
894
895     switch (genlmsghdr->cmd) {
896     case BRC_GENL_C_DP_ADD:
897         retval = handle_bridge_cmd(buffer, true);
898         break;
899
900     case BRC_GENL_C_DP_DEL:
901         retval = handle_bridge_cmd(buffer, false);
902         break;
903
904     case BRC_GENL_C_PORT_ADD:
905         retval = handle_port_cmd(buffer, true);
906         break;
907
908     case BRC_GENL_C_PORT_DEL:
909         retval = handle_port_cmd(buffer, false);
910         break;
911
912     case BRC_GENL_C_FDB_QUERY:
913         retval = handle_fdb_query_cmd(buffer);
914         break;
915
916     case BRC_GENL_C_GET_BRIDGES:
917         retval = handle_get_bridges_cmd(buffer);
918         break;
919
920     case BRC_GENL_C_GET_PORTS:
921         retval = handle_get_ports_cmd(buffer);
922         break;
923
924     default:
925         retval = EPROTO;
926     }
927
928     cfg_unlock();
929
930 error:
931     ofpbuf_delete(buffer);
932     return retval;
933 }
934
935 /* Check for interface configuration changes announced through RTNL. */
936 static void
937 rtnl_recv_update(void)
938 {
939     struct ofpbuf *buf;
940
941     int error = nl_sock_recv(rtnl_sock, &buf, false);
942     if (error == EAGAIN) {
943         /* Nothing to do. */
944     } else if (error == ENOBUFS) {
945         VLOG_WARN_RL(&rl, "network monitor socket overflowed");
946     } else if (error) {
947         VLOG_WARN_RL(&rl, "error on network monitor socket: %s", 
948                 strerror(error));
949     } else {
950         struct nlattr *attrs[ARRAY_SIZE(rtnlgrp_link_policy)];
951         struct nlmsghdr *nlh;
952         struct ifinfomsg *iim;
953
954         nlh = ofpbuf_at(buf, 0, NLMSG_HDRLEN);
955         iim = ofpbuf_at(buf, NLMSG_HDRLEN, sizeof *iim);
956         if (!iim) {
957             VLOG_WARN_RL(&rl, "received bad rtnl message (no ifinfomsg)");
958             ofpbuf_delete(buf);
959             return;
960         } 
961     
962         if (!nl_policy_parse(buf, NLMSG_HDRLEN + sizeof(struct ifinfomsg),
963                              rtnlgrp_link_policy,
964                              attrs, ARRAY_SIZE(rtnlgrp_link_policy))) {
965             VLOG_WARN_RL(&rl,"received bad rtnl message (policy)");
966             ofpbuf_delete(buf);
967             return;
968         }
969         if (nlh->nlmsg_type == RTM_DELLINK && attrs[IFLA_MASTER]) {
970             const char *port_name = nl_attr_get_string(attrs[IFLA_IFNAME]);
971             char br_name[IFNAMSIZ];
972             uint32_t br_idx = nl_attr_get_u32(attrs[IFLA_MASTER]);
973
974             if (!if_indextoname(br_idx, br_name)) {
975                 ofpbuf_delete(buf);
976                 return;
977             }
978
979             if (cfg_lock(NULL, lock_timeout)) {
980                 /* Couldn't lock config file. */
981                 /* xxx this should try again and print error msg. */
982                 ofpbuf_delete(buf);
983                 return;
984             }
985
986             if (!netdev_exists(port_name)) {
987                 /* Network device is really gone. */
988                 struct svec ports;
989
990                 VLOG_INFO("network device %s destroyed, "
991                           "removing from bridge %s", port_name, br_name);
992
993                 svec_init(&ports);
994                 cfg_get_all_keys(&ports, "bridge.%s.port", br_name);
995                 svec_sort(&ports);
996                 if (svec_contains(&ports, port_name)) {
997                     del_port(br_name, port_name);
998                     rewrite_and_reload_config();
999                 }
1000                 svec_destroy(&ports);
1001             } else {
1002                 /* A network device by that name exists even though the kernel
1003                  * told us it had disappeared.  Probably, what happened was
1004                  * this:
1005                  *
1006                  *      1. Device destroyed.
1007                  *      2. Notification sent to us.
1008                  *      3. New device created with same name as old one.
1009                  *      4. ovs-brcompatd notified, removes device from bridge.
1010                  *
1011                  * There's no a priori reason that in this situation that the
1012                  * new device with the same name should remain in the bridge;
1013                  * on the contrary, that would be unexpected.  *But* there is
1014                  * one important situation where, if we do this, bad things
1015                  * happen.  This is the case of XenServer Tools version 5.0.0,
1016                  * which on boot of a Windows VM cause something like this to
1017                  * happen on the Xen host:
1018                  *
1019                  *      i. Create tap1.0 and vif1.0.
1020                  *      ii. Delete tap1.0.
1021                  *      iii. Delete vif1.0.
1022                  *      iv. Re-create vif1.0.
1023                  *
1024                  * (XenServer Tools 5.5.0 does not exhibit this behavior, and
1025                  * neither does a VM without Tools installed at all.@.)
1026                  *
1027                  * Steps iii and iv happen within a few seconds of each other.
1028                  * Step iv causes /etc/xensource/scripts/vif to run, which in
1029                  * turn calls ovs-cfg-mod to add the new device to the bridge.
1030                  * If step iv happens after step 4 (in our first list of
1031                  * steps), then all is well, but if it happens between 3 and 4
1032                  * (which can easily happen if ovs-brcompatd has to wait to
1033                  * lock the configuration file), then we will remove the new
1034                  * incarnation from the bridge instead of the old one!
1035                  *
1036                  * So, to avoid this problem, we do nothing here.  This is
1037                  * strictly incorrect except for this one particular case, and
1038                  * perhaps that will bite us someday.  If that happens, then we
1039                  * will have to somehow track network devices by ifindex, since
1040                  * a new device will have a new ifindex even if it has the same
1041                  * name as an old device.
1042                  */
1043                 VLOG_INFO("kernel reported network device %s removed but "
1044                           "a device by that name exists (XS Tools 5.0.0?)",
1045                           port_name);
1046             }
1047             cfg_unlock();
1048         }
1049         ofpbuf_delete(buf);
1050     }
1051 }
1052
1053 int
1054 main(int argc, char *argv[])
1055 {
1056     struct unixctl_server *unixctl;
1057     int retval;
1058
1059     set_program_name(argv[0]);
1060     register_fault_handlers();
1061     time_init();
1062     vlog_init();
1063     parse_options(argc, argv);
1064     signal(SIGPIPE, SIG_IGN);
1065     process_init();
1066
1067     die_if_already_running();
1068     daemonize();
1069
1070     retval = unixctl_server_create(NULL, &unixctl);
1071     if (retval) {
1072         ovs_fatal(retval, "could not listen for vlog connections");
1073     }
1074
1075     if (brc_open(&brc_sock)) {
1076         ovs_fatal(0, "could not open brcompat socket.  Check "
1077                 "\"brcompat\" kernel module.");
1078     }
1079
1080     if (prune_timeout) {
1081         if (nl_sock_create(NETLINK_ROUTE, RTNLGRP_LINK, 0, 0, &rtnl_sock)) {
1082             ovs_fatal(0, "could not create rtnetlink socket");
1083         }
1084     }
1085
1086     retval = cfg_read();
1087     if (retval) {
1088         ovs_fatal(retval, "could not read config file");
1089     }
1090
1091     for (;;) {
1092         unixctl_server_run(unixctl);
1093         brc_recv_update();
1094         netdev_run();
1095
1096         /* If 'prune_timeout' is non-zero, we actively prune from the
1097          * config file any 'bridge.<br_name>.port' entries that are no 
1098          * longer valid.  We use two methods: 
1099          *
1100          *   1) The kernel explicitly notifies us of removed ports
1101          *      through the RTNL messages.
1102          *
1103          *   2) We periodically check all ports associated with bridges
1104          *      to see if they no longer exist.
1105          */
1106         if (prune_timeout) {
1107             rtnl_recv_update();
1108             prune_ports();
1109
1110             nl_sock_wait(rtnl_sock, POLLIN);
1111             poll_timer_wait(prune_timeout);
1112         }
1113
1114         nl_sock_wait(brc_sock, POLLIN);
1115         unixctl_server_wait(unixctl);
1116         netdev_wait();
1117         poll_block();
1118     }
1119
1120     return 0;
1121 }
1122
1123 static void
1124 validate_appctl_command(void)
1125 {
1126     const char *p;
1127     int n;
1128
1129     n = 0;
1130     for (p = strchr(appctl_command, '%'); p; p = strchr(p + 2, '%')) {
1131         if (p[1] == '%') {
1132             /* Nothing to do. */
1133         } else if (p[1] == 's') {
1134             n++;
1135         } else {
1136             ovs_fatal(0, "only '%%s' and '%%%%' allowed in --appctl-command");
1137         }
1138     }
1139     if (n != 1) {
1140         ovs_fatal(0, "'%%s' must appear exactly once in --appctl-command");
1141     }
1142 }
1143
1144 static void
1145 parse_options(int argc, char *argv[])
1146 {
1147     enum {
1148         OPT_LOCK_TIMEOUT = UCHAR_MAX + 1,
1149         OPT_PRUNE_TIMEOUT,
1150         OPT_APPCTL_COMMAND,
1151         VLOG_OPTION_ENUMS,
1152         LEAK_CHECKER_OPTION_ENUMS
1153     };
1154     static struct option long_options[] = {
1155         {"help",             no_argument, 0, 'h'},
1156         {"version",          no_argument, 0, 'V'},
1157         {"lock-timeout",     required_argument, 0, OPT_LOCK_TIMEOUT},
1158         {"prune-timeout",    required_argument, 0, OPT_PRUNE_TIMEOUT},
1159         {"appctl-command",   required_argument, 0, OPT_APPCTL_COMMAND},
1160         DAEMON_LONG_OPTIONS,
1161         VLOG_LONG_OPTIONS,
1162         LEAK_CHECKER_LONG_OPTIONS,
1163         {0, 0, 0, 0},
1164     };
1165     char *short_options = long_options_to_short_options(long_options);
1166     int error;
1167
1168     appctl_command = xasprintf("%s/ovs-appctl -t "
1169                                "%s/ovs-vswitchd.`cat %s/ovs-vswitchd.pid`.ctl "
1170                                "-e '%%s'",
1171                                ovs_bindir, ovs_rundir, ovs_rundir);
1172     for (;;) {
1173         int c;
1174
1175         c = getopt_long(argc, argv, short_options, long_options, NULL);
1176         if (c == -1) {
1177             break;
1178         }
1179
1180         switch (c) {
1181         case 'H':
1182         case 'h':
1183             usage();
1184
1185         case 'V':
1186             OVS_PRINT_VERSION(0, 0);
1187             exit(EXIT_SUCCESS);
1188
1189         case OPT_LOCK_TIMEOUT:
1190             lock_timeout = atoi(optarg);
1191             break;
1192
1193         case OPT_PRUNE_TIMEOUT:
1194             prune_timeout = atoi(optarg) * 1000;
1195             break;
1196
1197         case OPT_APPCTL_COMMAND:
1198             appctl_command = optarg;
1199             break;
1200
1201         VLOG_OPTION_HANDLERS
1202         DAEMON_OPTION_HANDLERS
1203         LEAK_CHECKER_OPTION_HANDLERS
1204
1205         case '?':
1206             exit(EXIT_FAILURE);
1207
1208         default:
1209             abort();
1210         }
1211     }
1212     free(short_options);
1213
1214     validate_appctl_command();
1215
1216     argc -= optind;
1217     argv += optind;
1218
1219     if (argc != 1) {
1220         ovs_fatal(0, "exactly one non-option argument required; "
1221                 "use --help for usage");
1222     }
1223
1224     cfg_init();
1225     config_file = argv[0];
1226     error = cfg_set_file(config_file);
1227     if (error) {
1228         ovs_fatal(error, "failed to add configuration file \"%s\"", 
1229                 config_file);
1230     }
1231 }
1232
1233 static void
1234 usage(void)
1235 {
1236     printf("%s: bridge compatibility front-end for ovs-vswitchd\n"
1237            "usage: %s [OPTIONS] CONFIG\n"
1238            "CONFIG is the configuration file used by ovs-vswitchd.\n",
1239            program_name, program_name);
1240     printf("\nConfiguration options:\n"
1241            "  --appctl-command=COMMAND  shell command to run ovs-appctl\n"
1242            "  --prune-timeout=SECS    wait at most SECS before pruning ports\n"
1243            "  --lock-timeout=MSECS    wait at most MSECS for CONFIG to unlock\n"
1244           );
1245     daemon_usage();
1246     vlog_usage();
1247     printf("\nOther options:\n"
1248            "  -h, --help              display this help message\n"
1249            "  -V, --version           display version information\n");
1250     leak_checker_usage();
1251     printf("\nThe default appctl command is:\n%s\n", appctl_command);
1252     exit(EXIT_SUCCESS);
1253 }