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