netdev: New function netdev_exists().
[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 /* Get all the interfaces for 'bridge' as 'ifaces', breaking bonded interfaces
244  * down into their constituent parts.
245  *
246  * If 'vlan' < 0, all interfaces on 'bridge' are reported.  If 'vlan' == 0,
247  * then only interfaces for trunk ports or ports with implicit VLAN 0 are
248  * reported.  If 'vlan' > 0, only interfaces with implict VLAN 'vlan' are
249  * reported.  */
250 static void
251 get_bridge_ifaces(const char *bridge, struct svec *ifaces, int vlan)
252 {
253     struct svec ports;
254     int i;
255
256     svec_init(&ports);
257     svec_init(ifaces);
258     cfg_get_all_keys(&ports, "bridge.%s.port", bridge);
259     for (i = 0; i < ports.n; i++) {
260         const char *port_name = ports.names[i];
261         if (vlan >= 0) {
262             int port_vlan = cfg_get_vlan(0, "vlan.%s.tag", port_name);
263             if (port_vlan < 0) {
264                 port_vlan = 0;
265             }
266             if (vlan != port_vlan) {
267                 continue;
268             }
269         }
270         if (cfg_has_section("bonding.%s", port_name)) {
271             struct svec slaves;
272             svec_init(&slaves);
273             cfg_get_all_keys(&slaves, "bonding.%s.slave", port_name);
274             svec_append(ifaces, &slaves);
275             svec_destroy(&slaves);
276         } else {
277             svec_add(ifaces, port_name);
278         }
279     }
280     svec_destroy(&ports);
281 }
282
283 /* Go through the configuration file and remove any ports that no longer
284  * exist associated with a bridge. */
285 static void
286 prune_ports(void)
287 {
288     int i, j;
289     struct svec bridges, delete;
290
291     if (cfg_lock(NULL, 0)) {
292         /* Couldn't lock config file. */
293         return;
294     }
295
296     svec_init(&bridges);
297     svec_init(&delete);
298     cfg_get_subsections(&bridges, "bridge");
299     for (i=0; i<bridges.n; i++) {
300         const char *br_name = bridges.names[i];
301         struct svec ifaces;
302
303         /* Check that each bridge interface exists. */
304         get_bridge_ifaces(br_name, &ifaces, -1);
305         for (j = 0; j < ifaces.n; j++) {
306             const char *iface_name = ifaces.names[j];
307
308             /* The local port and internal ports are created and destroyed by
309              * ovs-vswitchd itself, so don't bother checking for them at all.
310              * In practice, they might not exist if ovs-vswitchd hasn't
311              * finished reloading since the configuration file was updated. */
312             if (!strcmp(iface_name, br_name)
313                 || cfg_get_bool(0, "iface.%s.internal", iface_name)) {
314                 continue;
315             }
316
317             if (!netdev_exists(iface_name)) {
318                 VLOG_INFO_RL(&rl, "removing dead interface %s from %s",
319                              iface_name, br_name);
320                 svec_add(&delete, iface_name);
321             }
322         }
323         svec_destroy(&ifaces);
324     }
325     svec_destroy(&bridges);
326
327     if (delete.n) {
328         size_t i;
329
330         for (i = 0; i < delete.n; i++) {
331             cfg_del_match("bridge.*.port=%s", delete.names[i]);
332             cfg_del_match("bonding.*.slave=%s", delete.names[i]);
333         }
334         rewrite_and_reload_config();
335         cfg_unlock();
336     } else {
337         cfg_unlock();
338     }
339     svec_destroy(&delete);
340 }
341
342 static int
343 add_bridge(const char *br_name)
344 {
345     if (bridge_exists(br_name)) {
346         VLOG_WARN("addbr %s: bridge %s exists", br_name, br_name);
347         return EEXIST;
348     } else if (netdev_exists(br_name)) {
349         if (cfg_get_bool(0, "iface.%s.fake-bridge", br_name)) {
350             VLOG_WARN("addbr %s: %s exists as a fake bridge",
351                       br_name, br_name);
352             return 0;
353         } else {
354             VLOG_WARN("addbr %s: cannot create bridge %s because a network "
355                       "device named %s already exists",
356                       br_name, br_name, br_name);
357             return EEXIST;
358         }
359     }
360
361     cfg_add_entry("bridge.%s.port=%s", br_name, br_name);
362     VLOG_INFO("addbr %s: success", br_name);
363
364     return 0;
365 }
366
367 static int 
368 del_bridge(const char *br_name)
369 {
370     if (!bridge_exists(br_name)) {
371         VLOG_WARN("delbr %s: no bridge named %s", br_name, br_name);
372         return ENXIO;
373     }
374
375     cfg_del_section("bridge.%s", br_name);
376     VLOG_INFO("delbr %s: success", br_name);
377
378     return 0;
379 }
380
381 static int
382 parse_command(struct ofpbuf *buffer, uint32_t *seq, const char **br_name,
383               const char **port_name, uint64_t *count, uint64_t *skip)
384 {
385     static const struct nl_policy policy[] = {
386         [BRC_GENL_A_DP_NAME] = { .type = NL_A_STRING },
387         [BRC_GENL_A_PORT_NAME] = { .type = NL_A_STRING, .optional = true },
388         [BRC_GENL_A_FDB_COUNT] = { .type = NL_A_U64, .optional = true },
389         [BRC_GENL_A_FDB_SKIP] = { .type = NL_A_U64, .optional = true },
390     };
391     struct nlattr *attrs[ARRAY_SIZE(policy)];
392
393     if (!nl_policy_parse(buffer, NLMSG_HDRLEN + GENL_HDRLEN, policy,
394                          attrs, ARRAY_SIZE(policy))
395         || (port_name && !attrs[BRC_GENL_A_PORT_NAME])
396         || (count && !attrs[BRC_GENL_A_FDB_COUNT])
397         || (skip && !attrs[BRC_GENL_A_FDB_SKIP])) {
398         return EINVAL;
399     }
400
401     *seq = ((struct nlmsghdr *) buffer->data)->nlmsg_seq;
402     *br_name = nl_attr_get_string(attrs[BRC_GENL_A_DP_NAME]);
403     if (port_name) {
404         *port_name = nl_attr_get_string(attrs[BRC_GENL_A_PORT_NAME]);
405     }
406     if (count) {
407         *count = nl_attr_get_u64(attrs[BRC_GENL_A_FDB_COUNT]);
408     }
409     if (skip) {
410         *skip = nl_attr_get_u64(attrs[BRC_GENL_A_FDB_SKIP]);
411     }
412     return 0;
413 }
414
415 static void
416 send_reply(uint32_t seq, int error, struct ofpbuf *fdb_query_data)
417 {
418     struct ofpbuf msg;
419     int retval;
420
421     /* Compose reply. */
422     ofpbuf_init(&msg, 0);
423     nl_msg_put_genlmsghdr(&msg, brc_sock, 32, brc_family, NLM_F_REQUEST,
424                           BRC_GENL_C_DP_RESULT, 1);
425     ((struct nlmsghdr *) msg.data)->nlmsg_seq = seq;
426     nl_msg_put_u32(&msg, BRC_GENL_A_ERR_CODE, error);
427     if (fdb_query_data) {
428         nl_msg_put_unspec(&msg, BRC_GENL_A_FDB_DATA,
429                           fdb_query_data->data, fdb_query_data->size);
430     }
431
432     /* Send reply. */
433     retval = nl_sock_send(brc_sock, &msg, false);
434     if (retval) {
435         VLOG_WARN_RL(&rl, "replying to brcompat request: %s",
436                      strerror(retval));
437     }
438     ofpbuf_uninit(&msg);
439 }
440
441 static int
442 handle_bridge_cmd(struct ofpbuf *buffer, bool add)
443 {
444     const char *br_name;
445     uint32_t seq;
446     int error;
447
448     error = parse_command(buffer, &seq, &br_name, NULL, NULL, NULL);
449     if (!error) {
450         error = add ? add_bridge(br_name) : del_bridge(br_name);
451         if (!error) {
452             error = rewrite_and_reload_config();
453         }
454         send_reply(seq, error, NULL);
455     }
456     return error;
457 }
458
459 static const struct nl_policy brc_port_policy[] = {
460     [BRC_GENL_A_DP_NAME] = { .type = NL_A_STRING },
461     [BRC_GENL_A_PORT_NAME] = { .type = NL_A_STRING },
462 };
463
464 static void
465 del_port(const char *br_name, const char *port_name)
466 {
467     cfg_del_entry("bridge.%s.port=%s", br_name, port_name);
468     cfg_del_match("bonding.*.slave=%s", port_name);
469     cfg_del_match("vlan.%s.*", port_name);
470 }
471
472 static int
473 handle_port_cmd(struct ofpbuf *buffer, bool add)
474 {
475     const char *cmd_name = add ? "add-if" : "del-if";
476     const char *br_name, *port_name;
477     uint32_t seq;
478     int error;
479
480     error = parse_command(buffer, &seq, &br_name, &port_name, NULL, NULL);
481     if (!error) {
482         if (!bridge_exists(br_name)) {
483             VLOG_WARN("%s %s %s: no bridge named %s",
484                       cmd_name, br_name, port_name, br_name);
485             error = EINVAL;
486         } else if (!netdev_exists(port_name)) {
487             VLOG_WARN("%s %s %s: no network device named %s",
488                       cmd_name, br_name, port_name, port_name);
489             error = EINVAL;
490         } else {
491             if (add) {
492                 cfg_add_entry("bridge.%s.port=%s", br_name, port_name);
493             } else {
494                 del_port(br_name, port_name);
495             }
496             VLOG_INFO("%s %s %s: success", cmd_name, br_name, port_name);
497             error = rewrite_and_reload_config();
498         }
499         send_reply(seq, error, NULL);
500     }
501
502     return error;
503 }
504
505 /* Returns the name of the bridge that contains a port named 'port_name', as a
506  * malloc'd string that the caller must free, or a null pointer if no bridge
507  * contains a port named 'port_name'. */
508 static char *
509 get_bridge_containing_port(const char *port_name)
510 {
511     struct svec matches;
512     const char *start, *end;
513
514     svec_init(&matches);
515     cfg_get_matches(&matches, "bridge.*.port=%s", port_name);
516     if (!matches.n) {
517         return 0;
518     }
519
520     start = matches.names[0] + strlen("bridge.");
521     end = strstr(start, ".port=");
522     assert(end);
523     return xmemdup0(start, end - start);
524 }
525
526 static int
527 handle_fdb_query_cmd(struct ofpbuf *buffer)
528 {
529     /* This structure is copied directly from the Linux 2.6.30 header files.
530      * It would be more straightforward to #include <linux/if_bridge.h>, but
531      * the 'port_hi' member was only introduced in Linux 2.6.26 and so systems
532      * with old header files won't have it. */
533     struct __fdb_entry {
534         __u8 mac_addr[6];
535         __u8 port_no;
536         __u8 is_local;
537         __u32 ageing_timer_value;
538         __u8 port_hi;
539         __u8 pad0;
540         __u16 unused;
541     };
542
543     struct mac {
544         uint8_t addr[6];
545     };
546     struct mac *local_macs;
547     int n_local_macs;
548     int i;
549
550     /* Impedance matching between the vswitchd and Linux kernel notions of what
551      * a bridge is.  The kernel only handles a single VLAN per bridge, but
552      * vswitchd can deal with all the VLANs on a single bridge.  We have to
553      * pretend that the former is the case even though the latter is the
554      * implementation. */
555     const char *linux_bridge;   /* Name used by brctl. */
556     char *ovs_bridge;           /* Name used by ovs-vswitchd. */
557     int br_vlan;                /* VLAN tag. */
558     struct svec ifaces;
559
560     struct ofpbuf query_data;
561     char *unixctl_command;
562     uint64_t count, skip;
563     char *output;
564     char *save_ptr;
565     uint32_t seq;
566     int error;
567
568     /* Parse the command received from brcompat_mod. */
569     error = parse_command(buffer, &seq, &linux_bridge, NULL, &count, &skip);
570     if (error) {
571         return error;
572     }
573
574     /* Figure out vswitchd bridge and VLAN. */
575     cfg_read();
576     if (bridge_exists(linux_bridge)) {
577         /* Bridge name is the same.  We are interested in VLAN 0. */
578         ovs_bridge = xstrdup(linux_bridge);
579         br_vlan = 0;
580     } else {
581         /* No such Open vSwitch bridge 'linux_bridge', but there might be an
582          * internal port named 'linux_bridge' on some other bridge
583          * 'ovs_bridge'.  If so then we are interested in the VLAN assigned to
584          * port 'linux_bridge' on the bridge named 'ovs_bridge'. */
585         const char *port_name = linux_bridge;
586
587         ovs_bridge = get_bridge_containing_port(port_name);
588         br_vlan = cfg_get_vlan(0, "vlan.%s.tag", port_name);
589         if (!ovs_bridge || br_vlan < 0) {
590             free(ovs_bridge);
591             send_reply(seq, ENODEV, NULL);
592             return error;
593         }
594     }
595
596     /* Fetch the forwarding database using ovs-appctl. */
597     unixctl_command = xasprintf("fdb/show %s", ovs_bridge);
598     error = execute_appctl_command(unixctl_command, &output);
599     free(unixctl_command);
600     if (error) {
601         free(ovs_bridge);
602         send_reply(seq, error, NULL);
603         return error;
604     }
605
606     /* Fetch the MAC address for each interface on the bridge, so that we can
607      * fill in the is_local field in the response. */
608     get_bridge_ifaces(ovs_bridge, &ifaces, br_vlan);
609     local_macs = xmalloc(ifaces.n * sizeof *local_macs);
610     n_local_macs = 0;
611     for (i = 0; i < ifaces.n; i++) {
612         const char *iface_name = ifaces.names[i];
613         struct mac *mac = &local_macs[n_local_macs];
614         if (!netdev_nodev_get_etheraddr(iface_name, mac->addr)) {
615             n_local_macs++;
616         }
617     }
618     svec_destroy(&ifaces);
619
620     /* Parse the response from ovs-appctl and convert it to binary format to
621      * pass back to the kernel. */
622     ofpbuf_init(&query_data, sizeof(struct __fdb_entry) * 8);
623     save_ptr = NULL;
624     strtok_r(output, "\n", &save_ptr); /* Skip header line. */
625     while (count > 0) {
626         struct __fdb_entry *entry;
627         int port, vlan, age;
628         uint8_t mac[ETH_ADDR_LEN];
629         char *line;
630         bool is_local;
631
632         line = strtok_r(NULL, "\n", &save_ptr);
633         if (!line) {
634             break;
635         }
636
637         if (sscanf(line, "%d %d "ETH_ADDR_SCAN_FMT" %d",
638                    &port, &vlan, ETH_ADDR_SCAN_ARGS(mac), &age)
639             != 2 + ETH_ADDR_SCAN_COUNT + 1) {
640             struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 1);
641             VLOG_INFO_RL(&rl, "fdb/show output has invalid format: %s", line);
642             continue;
643         }
644
645         if (vlan != br_vlan) {
646             continue;
647         }
648
649         if (skip > 0) {
650             skip--;
651             continue;
652         }
653
654         /* Is this the MAC address of an interface on the bridge? */
655         is_local = false;
656         for (i = 0; i < n_local_macs; i++) {
657             if (eth_addr_equals(local_macs[i].addr, mac)) {
658                 is_local = true;
659                 break;
660             }
661         }
662
663         entry = ofpbuf_put_uninit(&query_data, sizeof *entry);
664         memcpy(entry->mac_addr, mac, ETH_ADDR_LEN);
665         entry->port_no = port & 0xff;
666         entry->is_local = is_local;
667         entry->ageing_timer_value = age * HZ;
668         entry->port_hi = (port & 0xff00) >> 8;
669         entry->pad0 = 0;
670         entry->unused = 0;
671         count--;
672     }
673     free(output);
674
675     send_reply(seq, 0, &query_data);
676     ofpbuf_uninit(&query_data);
677     free(ovs_bridge);
678
679     return 0;
680 }
681
682 static int
683 brc_recv_update(void)
684 {
685     int retval;
686     struct ofpbuf *buffer;
687     struct genlmsghdr *genlmsghdr;
688
689
690     buffer = NULL;
691     do {
692         ofpbuf_delete(buffer);
693         retval = nl_sock_recv(brc_sock, &buffer, false);
694     } while (retval == ENOBUFS
695             || (!retval
696                 && (nl_msg_nlmsgerr(buffer, NULL)
697                     || nl_msg_nlmsghdr(buffer)->nlmsg_type == NLMSG_DONE)));
698     if (retval) {
699         if (retval != EAGAIN) {
700             VLOG_WARN_RL(&rl, "brc_recv_update: %s", strerror(retval));
701         }
702         return retval;
703     }
704
705     genlmsghdr = nl_msg_genlmsghdr(buffer);
706     if (!genlmsghdr) {
707         VLOG_WARN_RL(&rl, "received packet too short for generic NetLink");
708         goto error;
709     }
710
711     if (nl_msg_nlmsghdr(buffer)->nlmsg_type != brc_family) {
712         VLOG_DBG_RL(&rl, "received type (%"PRIu16") != brcompat family (%d)",
713                 nl_msg_nlmsghdr(buffer)->nlmsg_type, brc_family);
714         goto error;
715     }
716
717     if (cfg_lock(NULL, lock_timeout)) {
718         /* Couldn't lock config file. */
719         retval = EAGAIN;
720         goto error;
721     }
722
723     switch (genlmsghdr->cmd) {
724     case BRC_GENL_C_DP_ADD:
725         retval = handle_bridge_cmd(buffer, true);
726         break;
727
728     case BRC_GENL_C_DP_DEL:
729         retval = handle_bridge_cmd(buffer, false);
730         break;
731
732     case BRC_GENL_C_PORT_ADD:
733         retval = handle_port_cmd(buffer, true);
734         break;
735
736     case BRC_GENL_C_PORT_DEL:
737         retval = handle_port_cmd(buffer, false);
738         break;
739
740     case BRC_GENL_C_FDB_QUERY:
741         retval = handle_fdb_query_cmd(buffer);
742         break;
743
744     default:
745         retval = EPROTO;
746     }
747
748     cfg_unlock();
749
750 error:
751     ofpbuf_delete(buffer);
752     return retval;
753 }
754
755 /* Check for interface configuration changes announced through RTNL. */
756 static void
757 rtnl_recv_update(void)
758 {
759     struct ofpbuf *buf;
760
761     int error = nl_sock_recv(rtnl_sock, &buf, false);
762     if (error == EAGAIN) {
763         /* Nothing to do. */
764     } else if (error == ENOBUFS) {
765         VLOG_WARN_RL(&rl, "network monitor socket overflowed");
766     } else if (error) {
767         VLOG_WARN_RL(&rl, "error on network monitor socket: %s", 
768                 strerror(error));
769     } else {
770         struct nlattr *attrs[ARRAY_SIZE(rtnlgrp_link_policy)];
771         struct nlmsghdr *nlh;
772         struct ifinfomsg *iim;
773
774         nlh = ofpbuf_at(buf, 0, NLMSG_HDRLEN);
775         iim = ofpbuf_at(buf, NLMSG_HDRLEN, sizeof *iim);
776         if (!iim) {
777             VLOG_WARN_RL(&rl, "received bad rtnl message (no ifinfomsg)");
778             ofpbuf_delete(buf);
779             return;
780         } 
781     
782         if (!nl_policy_parse(buf, NLMSG_HDRLEN + sizeof(struct ifinfomsg),
783                              rtnlgrp_link_policy,
784                              attrs, ARRAY_SIZE(rtnlgrp_link_policy))) {
785             VLOG_WARN_RL(&rl,"received bad rtnl message (policy)");
786             ofpbuf_delete(buf);
787             return;
788         }
789         if (nlh->nlmsg_type == RTM_DELLINK && attrs[IFLA_MASTER]) {
790             const char *port_name = nl_attr_get_string(attrs[IFLA_IFNAME]);
791             char br_name[IFNAMSIZ];
792             uint32_t br_idx = nl_attr_get_u32(attrs[IFLA_MASTER]);
793             struct svec ports;
794
795             if (!if_indextoname(br_idx, br_name)) {
796                 ofpbuf_delete(buf);
797                 return;
798             }
799
800             if (cfg_lock(NULL, lock_timeout)) {
801                 /* Couldn't lock config file. */
802                 /* xxx this should try again and print error msg. */
803                 ofpbuf_delete(buf);
804                 return;
805             }
806
807             if (!netdev_exists(port_name)) {
808                 /* Network device is really gone. */
809                 VLOG_INFO("network device %s destroyed, "
810                           "removing from bridge %s", port_name, br_name);
811                 svec_init(&ports);
812                 cfg_get_all_keys(&ports, "bridge.%s.port", br_name);
813                 svec_sort(&ports);
814                 if (svec_contains(&ports, port_name)) {
815                     del_port(br_name, port_name);
816                     rewrite_and_reload_config();
817                 }
818             } else {
819                 /* A network device by that name exists even though the kernel
820                  * told us it had disappeared.  Probably, what happened was
821                  * this:
822                  *
823                  *      1. Device destroyed.
824                  *      2. Notification sent to us.
825                  *      3. New device created with same name as old one.
826                  *      4. ovs-brcompatd notified, removes device from bridge.
827                  *
828                  * There's no a priori reason that in this situation that the
829                  * new device with the same name should remain in the bridge;
830                  * on the contrary, that would be unexpected.  *But* there is
831                  * one important situation where, if we do this, bad things
832                  * happen.  This is the case of XenServer Tools version 5.0.0,
833                  * which on boot of a Windows VM cause something like this to
834                  * happen on the Xen host:
835                  *
836                  *      i. Create tap1.0 and vif1.0.
837                  *      ii. Delete tap1.0.
838                  *      iii. Delete vif1.0.
839                  *      iv. Re-create vif1.0.
840                  *
841                  * (XenServer Tools 5.5.0 does not exhibit this behavior, and
842                  * neither does a VM without Tools installed at all.@.)
843                  *
844                  * Steps iii and iv happen within a few seconds of each other.
845                  * Step iv causes /etc/xensource/scripts/vif to run, which in
846                  * turn calls ovs-cfg-mod to add the new device to the bridge.
847                  * If step iv happens after step 4 (in our first list of
848                  * steps), then all is well, but if it happens between 3 and 4
849                  * (which can easily happen if ovs-brcompatd has to wait to
850                  * lock the configuration file), then we will remove the new
851                  * incarnation from the bridge instead of the old one!
852                  *
853                  * So, to avoid this problem, we do nothing here.  This is
854                  * strictly incorrect except for this one particular case, and
855                  * perhaps that will bite us someday.  If that happens, then we
856                  * will have to somehow track network devices by ifindex, since
857                  * a new device will have a new ifindex even if it has the same
858                  * name as an old device.
859                  */
860                 VLOG_INFO("kernel reported network device %s removed but "
861                           "a device by that name exists (XS Tools 5.0.0?)",
862                           port_name);
863             }
864             cfg_unlock();
865         }
866         ofpbuf_delete(buf);
867     }
868 }
869
870 int
871 main(int argc, char *argv[])
872 {
873     struct unixctl_server *unixctl;
874     int retval;
875
876     set_program_name(argv[0]);
877     register_fault_handlers();
878     time_init();
879     vlog_init();
880     parse_options(argc, argv);
881     signal(SIGPIPE, SIG_IGN);
882     process_init();
883
884     die_if_already_running();
885     daemonize();
886
887     retval = unixctl_server_create(NULL, &unixctl);
888     if (retval) {
889         ovs_fatal(retval, "could not listen for vlog connections");
890     }
891
892     if (brc_open(&brc_sock)) {
893         ovs_fatal(0, "could not open brcompat socket.  Check "
894                 "\"brcompat\" kernel module.");
895     }
896
897     if (prune_timeout) {
898         if (nl_sock_create(NETLINK_ROUTE, RTNLGRP_LINK, 0, 0, &rtnl_sock)) {
899             ovs_fatal(0, "could not create rtnetlink socket");
900         }
901     }
902
903     cfg_read();
904
905     for (;;) {
906         unixctl_server_run(unixctl);
907         brc_recv_update();
908
909         /* If 'prune_timeout' is non-zero, we actively prune from the
910          * config file any 'bridge.<br_name>.port' entries that are no 
911          * longer valid.  We use two methods: 
912          *
913          *   1) The kernel explicitly notifies us of removed ports
914          *      through the RTNL messages.
915          *
916          *   2) We periodically check all ports associated with bridges
917          *      to see if they no longer exist.
918          */
919         if (prune_timeout) {
920             rtnl_recv_update();
921             prune_ports();
922
923             nl_sock_wait(rtnl_sock, POLLIN);
924             poll_timer_wait(prune_timeout);
925         }
926
927         nl_sock_wait(brc_sock, POLLIN);
928         unixctl_server_wait(unixctl);
929         poll_block();
930     }
931
932     return 0;
933 }
934
935 static void
936 validate_appctl_command(void)
937 {
938     const char *p;
939     int n;
940
941     n = 0;
942     for (p = strchr(appctl_command, '%'); p; p = strchr(p + 2, '%')) {
943         if (p[1] == '%') {
944             /* Nothing to do. */
945         } else if (p[1] == 's') {
946             n++;
947         } else {
948             ovs_fatal(0, "only '%%s' and '%%%%' allowed in --appctl-command");
949         }
950     }
951     if (n != 1) {
952         ovs_fatal(0, "'%%s' must appear exactly once in --appctl-command");
953     }
954 }
955
956 static void
957 parse_options(int argc, char *argv[])
958 {
959     enum {
960         OPT_LOCK_TIMEOUT = UCHAR_MAX + 1,
961         OPT_PRUNE_TIMEOUT,
962         OPT_APPCTL_COMMAND,
963         VLOG_OPTION_ENUMS,
964         LEAK_CHECKER_OPTION_ENUMS
965     };
966     static struct option long_options[] = {
967         {"help",             no_argument, 0, 'h'},
968         {"version",          no_argument, 0, 'V'},
969         {"lock-timeout",     required_argument, 0, OPT_LOCK_TIMEOUT},
970         {"prune-timeout",    required_argument, 0, OPT_PRUNE_TIMEOUT},
971         {"appctl-command",   required_argument, 0, OPT_APPCTL_COMMAND},
972         DAEMON_LONG_OPTIONS,
973         VLOG_LONG_OPTIONS,
974         LEAK_CHECKER_LONG_OPTIONS,
975         {0, 0, 0, 0},
976     };
977     char *short_options = long_options_to_short_options(long_options);
978     int error;
979
980     appctl_command = xasprintf("%s/ovs-appctl -t "
981                                "%s/ovs-vswitchd.`cat %s/ovs-vswitchd.pid`.ctl "
982                                "-e '%%s'",
983                                ovs_bindir, ovs_rundir, ovs_rundir);
984     for (;;) {
985         int c;
986
987         c = getopt_long(argc, argv, short_options, long_options, NULL);
988         if (c == -1) {
989             break;
990         }
991
992         switch (c) {
993         case 'H':
994         case 'h':
995             usage();
996
997         case 'V':
998             OVS_PRINT_VERSION(0, 0);
999             exit(EXIT_SUCCESS);
1000
1001         case OPT_LOCK_TIMEOUT:
1002             lock_timeout = atoi(optarg);
1003             break;
1004
1005         case OPT_PRUNE_TIMEOUT:
1006             prune_timeout = atoi(optarg) * 1000;
1007             break;
1008
1009         case OPT_APPCTL_COMMAND:
1010             appctl_command = optarg;
1011             break;
1012
1013         VLOG_OPTION_HANDLERS
1014         DAEMON_OPTION_HANDLERS
1015         LEAK_CHECKER_OPTION_HANDLERS
1016
1017         case '?':
1018             exit(EXIT_FAILURE);
1019
1020         default:
1021             abort();
1022         }
1023     }
1024     free(short_options);
1025
1026     validate_appctl_command();
1027
1028     argc -= optind;
1029     argv += optind;
1030
1031     if (argc != 1) {
1032         ovs_fatal(0, "exactly one non-option argument required; "
1033                 "use --help for usage");
1034     }
1035
1036     config_file = argv[0];
1037     error = cfg_set_file(config_file);
1038     if (error) {
1039         ovs_fatal(error, "failed to add configuration file \"%s\"", 
1040                 config_file);
1041     }
1042 }
1043
1044 static void
1045 usage(void)
1046 {
1047     printf("%s: bridge compatibility front-end for ovs-vswitchd\n"
1048            "usage: %s [OPTIONS] CONFIG\n"
1049            "CONFIG is the configuration file used by ovs-vswitchd.\n",
1050            program_name, program_name);
1051     printf("\nConfiguration options:\n"
1052            "  --appctl-command=COMMAND  shell command to run ovs-appctl\n"
1053            "  --prune-timeout=SECS    wait at most SECS before pruning ports\n"
1054            "  --lock-timeout=MSECS    wait at most MSECS for CONFIG to unlock\n"
1055           );
1056     daemon_usage();
1057     vlog_usage();
1058     printf("\nOther options:\n"
1059            "  -h, --help              display this help message\n"
1060            "  -V, --version           display version information\n");
1061     leak_checker_usage();
1062     printf("\nThe default appctl command is:\n%s\n", appctl_command);
1063     exit(EXIT_SUCCESS);
1064 }