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