netdev: Get rid of struct netdev_options and netdev_open_default().
[sliver-openvswitch.git] / vswitchd / ovs-brcompatd.c
1 /* Copyright (c) 2008, 2009, 2010, 2011 Nicira Networks
2  *
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at:
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15
16 #include <config.h>
17
18 #include <asm/param.h>
19 #include <assert.h>
20 #include <errno.h>
21 #include <getopt.h>
22 #include <inttypes.h>
23 #include <limits.h>
24 #include <net/if.h>
25 #include <linux/genetlink.h>
26 #include <linux/rtnetlink.h>
27 #include <signal.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <sys/types.h>
31 #include <sys/stat.h>
32 #include <time.h>
33 #include <fcntl.h>
34 #include <unistd.h>
35
36 #include "command-line.h"
37 #include "coverage.h"
38 #include "daemon.h"
39 #include "dirs.h"
40 #include "dynamic-string.h"
41 #include "fatal-signal.h"
42 #include "json.h"
43 #include "leak-checker.h"
44 #include "netdev.h"
45 #include "netlink.h"
46 #include "netlink-socket.h"
47 #include "ofpbuf.h"
48 #include "openvswitch/brcompat-netlink.h"
49 #include "packets.h"
50 #include "poll-loop.h"
51 #include "process.h"
52 #include "rtnetlink.h"
53 #include "rtnetlink-link.h"
54 #include "signals.h"
55 #include "sset.h"
56 #include "svec.h"
57 #include "timeval.h"
58 #include "unixctl.h"
59 #include "util.h"
60 #include "vlog.h"
61
62 VLOG_DEFINE_THIS_MODULE(brcompatd);
63
64 /* xxx Just hangs if datapath is rmmod/insmod.  Learn to reconnect? */
65
66 static void parse_options(int argc, char *argv[]);
67 static void usage(void) NO_RETURN;
68
69 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 60);
70
71 /* --appctl: Absolute path to ovs-appctl. */
72 static char *appctl_program;
73
74 /* --vsctl: Absolute path to ovs-vsctl. */
75 static char *vsctl_program;
76
77 /* Options that we should generally pass to ovs-vsctl. */
78 #define VSCTL_OPTIONS "--timeout=5", "-vANY:console:WARN"
79
80 /* Netlink socket to bridge compatibility kernel module. */
81 static struct nl_sock *brc_sock;
82
83 /* The Generic Netlink family number used for bridge compatibility. */
84 static int brc_family;
85
86 static const struct nl_policy brc_multicast_policy[] = {
87     [BRC_GENL_A_MC_GROUP] = {.type = NL_A_U32 }
88 };
89
90 static char *
91 capture_vsctl_valist(const char *arg0, va_list args)
92 {
93     char *stdout_log, *stderr_log;
94     enum vlog_level log_level;
95     struct svec argv;
96     int status;
97     char *msg;
98
99     /* Compose arguments. */
100     svec_init(&argv);
101     svec_add(&argv, arg0);
102     for (;;) {
103         const char *arg = va_arg(args, const char *);
104         if (!arg) {
105             break;
106         }
107         svec_add(&argv, arg);
108     }
109     svec_terminate(&argv);
110
111     /* Run process. */
112     if (process_run_capture(argv.names, &stdout_log, &stderr_log, SIZE_MAX,
113                             &status)) {
114         svec_destroy(&argv);
115         return NULL;
116     }
117
118     /* Log results. */
119     if (WIFEXITED(status)) {
120         int code = WEXITSTATUS(status);
121         log_level = code == 0 ? VLL_DBG : code == 1 ? VLL_WARN : VLL_ERR;
122     } else {
123         log_level = VLL_ERR;
124     }
125     msg = process_status_msg(status);
126     VLOG(log_level, "ovs-vsctl exited (%s)", msg);
127     if (stdout_log && *stdout_log) {
128         VLOG(log_level, "ovs-vsctl wrote to stdout:\n%s\n", stdout_log);
129     }
130     if (stderr_log && *stderr_log) {
131         VLOG(log_level, "ovs-vsctl wrote to stderr:\n%s\n", stderr_log);
132     }
133     free(msg);
134
135     svec_destroy(&argv);
136
137     free(stderr_log);
138     if (WIFEXITED(status) && !WEXITSTATUS(status)) {
139         return stdout_log;
140     } else {
141         free(stdout_log);
142         return NULL;
143     }
144 }
145
146 static char * SENTINEL(0)
147 capture_vsctl(const char *arg0, ...)
148 {
149     char *stdout_log;
150     va_list args;
151
152     va_start(args, arg0);
153     stdout_log = capture_vsctl_valist(arg0, args);
154     va_end(args);
155
156     return stdout_log;
157 }
158
159 static bool SENTINEL(0)
160 run_vsctl(const char *arg0, ...)
161 {
162     char *stdout_log;
163     va_list args;
164     bool ok;
165
166     va_start(args, arg0);
167     stdout_log = capture_vsctl_valist(arg0, args);
168     va_end(args);
169
170     ok = stdout_log != NULL;
171     free(stdout_log);
172     return ok;
173 }
174
175 static int
176 lookup_brc_multicast_group(int *multicast_group)
177 {
178     struct nl_sock *sock;
179     struct ofpbuf request, *reply;
180     struct nlattr *attrs[ARRAY_SIZE(brc_multicast_policy)];
181     int retval;
182
183     retval = nl_sock_create(NETLINK_GENERIC, &sock);
184     if (retval) {
185         return retval;
186     }
187     ofpbuf_init(&request, 0);
188     nl_msg_put_genlmsghdr(&request, 0, brc_family,
189             NLM_F_REQUEST, BRC_GENL_C_QUERY_MC, 1);
190     retval = nl_sock_transact(sock, &request, &reply);
191     ofpbuf_uninit(&request);
192     if (retval) {
193         nl_sock_destroy(sock);
194         return retval;
195     }
196     if (!nl_policy_parse(reply, NLMSG_HDRLEN + GENL_HDRLEN,
197                          brc_multicast_policy, attrs,
198                          ARRAY_SIZE(brc_multicast_policy))) {
199         nl_sock_destroy(sock);
200         ofpbuf_delete(reply);
201         return EPROTO;
202     }
203     *multicast_group = nl_attr_get_u32(attrs[BRC_GENL_A_MC_GROUP]);
204     nl_sock_destroy(sock);
205     ofpbuf_delete(reply);
206
207     return 0;
208 }
209
210 /* Opens a socket for brcompat notifications.  Returns 0 if successful,
211  * otherwise a positive errno value. */
212 static int
213 brc_open(struct nl_sock **sock)
214 {
215     int multicast_group = 0;
216     int retval;
217
218     retval = nl_lookup_genl_family(BRC_GENL_FAMILY_NAME, &brc_family);
219     if (retval) {
220         return retval;
221     }
222
223     retval = lookup_brc_multicast_group(&multicast_group);
224     if (retval) {
225         return retval;
226     }
227
228     retval = nl_sock_create(NETLINK_GENERIC, sock);
229     if (retval) {
230         return retval;
231     }
232
233     retval = nl_sock_join_mcgroup(*sock, multicast_group);
234     if (retval) {
235         nl_sock_destroy(*sock);
236         *sock = NULL;
237     }
238     return retval;
239 }
240
241 static const struct nl_policy brc_dp_policy[] = {
242     [BRC_GENL_A_DP_NAME] = { .type = NL_A_STRING },
243 };
244
245 static int
246 parse_command(struct ofpbuf *buffer, uint32_t *seq, const char **br_name,
247               const char **port_name, uint64_t *count, uint64_t *skip)
248 {
249     static const struct nl_policy policy[] = {
250         [BRC_GENL_A_DP_NAME] = { .type = NL_A_STRING, .optional = true },
251         [BRC_GENL_A_PORT_NAME] = { .type = NL_A_STRING, .optional = true },
252         [BRC_GENL_A_FDB_COUNT] = { .type = NL_A_U64, .optional = true },
253         [BRC_GENL_A_FDB_SKIP] = { .type = NL_A_U64, .optional = true },
254     };
255     struct nlattr *attrs[ARRAY_SIZE(policy)];
256
257     if (!nl_policy_parse(buffer, NLMSG_HDRLEN + GENL_HDRLEN, policy,
258                          attrs, ARRAY_SIZE(policy))
259         || (br_name && !attrs[BRC_GENL_A_DP_NAME])
260         || (port_name && !attrs[BRC_GENL_A_PORT_NAME])
261         || (count && !attrs[BRC_GENL_A_FDB_COUNT])
262         || (skip && !attrs[BRC_GENL_A_FDB_SKIP])) {
263         return EINVAL;
264     }
265
266     *seq = ((struct nlmsghdr *) buffer->data)->nlmsg_seq;
267     if (br_name) {
268         *br_name = nl_attr_get_string(attrs[BRC_GENL_A_DP_NAME]);
269     }
270     if (port_name) {
271         *port_name = nl_attr_get_string(attrs[BRC_GENL_A_PORT_NAME]);
272     }
273     if (count) {
274         *count = nl_attr_get_u64(attrs[BRC_GENL_A_FDB_COUNT]);
275     }
276     if (skip) {
277         *skip = nl_attr_get_u64(attrs[BRC_GENL_A_FDB_SKIP]);
278     }
279     return 0;
280 }
281
282 /* Composes and returns a reply to a request made by the datapath with Netlink
283  * sequence number 'seq' and error code 'error'.  The caller may add additional
284  * attributes to the message, then it may send it with send_reply(). */
285 static struct ofpbuf *
286 compose_reply(uint32_t seq, int error)
287 {
288     struct ofpbuf *reply = ofpbuf_new(4096);
289     nl_msg_put_genlmsghdr(reply, 32, brc_family, NLM_F_REQUEST,
290                           BRC_GENL_C_DP_RESULT, 1);
291     ((struct nlmsghdr *) reply->data)->nlmsg_seq = seq;
292     nl_msg_put_u32(reply, BRC_GENL_A_ERR_CODE, error);
293     return reply;
294 }
295
296 /* Sends 'reply' to the datapath and frees it. */
297 static void
298 send_reply(struct ofpbuf *reply)
299 {
300     int retval = nl_sock_send(brc_sock, reply, false);
301     if (retval) {
302         VLOG_WARN_RL(&rl, "replying to brcompat request: %s",
303                      strerror(retval));
304     }
305     ofpbuf_delete(reply);
306 }
307
308 /* Composes and sends a reply to a request made by the datapath with Netlink
309  * sequence number 'seq' and error code 'error'. */
310 static void
311 send_simple_reply(uint32_t seq, int error)
312 {
313     send_reply(compose_reply(seq, error));
314 }
315
316 static int
317 handle_bridge_cmd(struct ofpbuf *buffer, bool add)
318 {
319     const char *br_name;
320     uint32_t seq;
321     int error;
322
323     error = parse_command(buffer, &seq, &br_name, NULL, NULL, NULL);
324     if (!error) {
325         const char *vsctl_cmd = add ? "add-br" : "del-br";
326         const char *brctl_cmd = add ? "addbr" : "delbr";
327         if (!run_vsctl(vsctl_program, VSCTL_OPTIONS,
328                        "--", vsctl_cmd, br_name,
329                        "--", "comment", "ovs-brcompatd:", brctl_cmd, br_name,
330                        (char *) NULL)) {
331             error = add ? EEXIST : ENXIO;
332         }
333         send_simple_reply(seq, error);
334     }
335     return error;
336 }
337
338 static const struct nl_policy brc_port_policy[] = {
339     [BRC_GENL_A_DP_NAME] = { .type = NL_A_STRING },
340     [BRC_GENL_A_PORT_NAME] = { .type = NL_A_STRING },
341 };
342
343 static int
344 handle_port_cmd(struct ofpbuf *buffer, bool add)
345 {
346     const char *br_name, *port_name;
347     uint32_t seq;
348     int error;
349
350     error = parse_command(buffer, &seq, &br_name, &port_name, NULL, NULL);
351     if (!error) {
352         const char *vsctl_cmd = add ? "add-port" : "del-port";
353         const char *brctl_cmd = add ? "addif" : "delif";
354         if (!run_vsctl(vsctl_program, VSCTL_OPTIONS,
355                        "--", vsctl_cmd, br_name, port_name,
356                        "--", "comment", "ovs-brcompatd:", brctl_cmd,
357                        br_name, port_name, (char *) NULL)) {
358             error = EINVAL;
359         }
360         send_simple_reply(seq, error);
361     }
362     return error;
363 }
364
365 static char *
366 linux_bridge_to_ovs_bridge(const char *linux_name, int *br_vlanp)
367 {
368     char *save_ptr = NULL;
369     const char *br_name, *br_vlan;
370     char *br_name_copy;
371     char *output;
372
373     output = capture_vsctl(vsctl_program, VSCTL_OPTIONS,
374                            "--", "br-to-parent", linux_name,
375                            "--", "br-to-vlan", linux_name,
376                            (char *) NULL);
377     if (!output) {
378         return NULL;
379     }
380
381     br_name = strtok_r(output, " \t\r\n", &save_ptr);
382     br_vlan = strtok_r(NULL, " \t\r\n", &save_ptr);
383     if (!br_name || !br_vlan) {
384         free(output);
385         return NULL;
386     }
387     br_name_copy = xstrdup(br_name);
388     *br_vlanp = atoi(br_vlan);
389
390     free(output);
391
392     return br_name_copy;
393 }
394
395 static void
396 get_bridge_ifaces(const char *br_name, struct sset *ifaces)
397 {
398     char *save_ptr = NULL;
399     char *output;
400     char *iface;
401
402     output = capture_vsctl(vsctl_program, VSCTL_OPTIONS, "list-ifaces",
403                            br_name, (char *) NULL);
404     if (!output) {
405         return;
406     }
407
408     for (iface = strtok_r(output, " \t\r\n", &save_ptr); iface;
409          iface = strtok_r(NULL, " \t\r\n", &save_ptr)) {
410         sset_add(ifaces, iface);
411     }
412     free(output);
413 }
414
415 static int
416 handle_fdb_query_cmd(struct ofpbuf *buffer)
417 {
418     /* This structure is copied directly from the Linux 2.6.30 header files.
419      * It would be more straightforward to #include <linux/if_bridge.h>, but
420      * the 'port_hi' member was only introduced in Linux 2.6.26 and so systems
421      * with old header files won't have it. */
422     struct __fdb_entry {
423         __u8 mac_addr[6];
424         __u8 port_no;
425         __u8 is_local;
426         __u32 ageing_timer_value;
427         __u8 port_hi;
428         __u8 pad0;
429         __u16 unused;
430     };
431
432     struct mac {
433         uint8_t addr[6];
434     };
435     struct mac *local_macs;
436     int n_local_macs;
437     int i;
438
439     /* Impedance matching between the vswitchd and Linux kernel notions of what
440      * a bridge is.  The kernel only handles a single VLAN per bridge, but
441      * vswitchd can deal with all the VLANs on a single bridge.  We have to
442      * pretend that the former is the case even though the latter is the
443      * implementation. */
444     const char *linux_name;   /* Name used by brctl. */
445     int br_vlan;                /* VLAN tag. */
446     struct sset ifaces;
447
448     struct ofpbuf query_data;
449     const char *iface_name;
450     struct ofpbuf *reply;
451     uint64_t count, skip;
452     char *br_name;
453     char *output;
454     char *save_ptr;
455     uint32_t seq;
456     int error;
457
458     /* Parse the command received from brcompat_mod. */
459     error = parse_command(buffer, &seq, &linux_name, NULL, &count, &skip);
460     if (error) {
461         return error;
462     }
463
464     /* Figure out vswitchd bridge and VLAN. */
465     br_name = linux_bridge_to_ovs_bridge(linux_name, &br_vlan);
466     if (!br_name) {
467         error = EINVAL;
468         send_simple_reply(seq, error);
469         return error;
470     }
471
472     /* Fetch the forwarding database using ovs-appctl. */
473     output = capture_vsctl(appctl_program, "fdb/show", br_name,
474                            (char *) NULL);
475     if (!output) {
476         error = ECHILD;
477         send_simple_reply(seq, error);
478         return error;
479     }
480
481     /* Fetch the MAC address for each interface on the bridge, so that we can
482      * fill in the is_local field in the response. */
483     sset_init(&ifaces);
484     get_bridge_ifaces(linux_name, &ifaces);
485     local_macs = xmalloc(sset_count(&ifaces) * sizeof *local_macs);
486     n_local_macs = 0;
487     SSET_FOR_EACH (iface_name, &ifaces) {
488         struct mac *mac = &local_macs[n_local_macs];
489         struct netdev *netdev;
490
491         error = netdev_open(iface_name, "system", &netdev);
492         if (!error) {
493             if (!netdev_get_etheraddr(netdev, mac->addr)) {
494                 n_local_macs++;
495             }
496             netdev_close(netdev);
497         }
498     }
499     sset_destroy(&ifaces);
500
501     /* Parse the response from ovs-appctl and convert it to binary format to
502      * pass back to the kernel. */
503     ofpbuf_init(&query_data, sizeof(struct __fdb_entry) * 8);
504     save_ptr = NULL;
505     strtok_r(output, "\n", &save_ptr); /* Skip header line. */
506     while (count > 0) {
507         struct __fdb_entry *entry;
508         int port, vlan, age;
509         uint8_t mac[ETH_ADDR_LEN];
510         char *line;
511         bool is_local;
512
513         line = strtok_r(NULL, "\n", &save_ptr);
514         if (!line) {
515             break;
516         }
517
518         if (sscanf(line, "%d %d "ETH_ADDR_SCAN_FMT" %d",
519                    &port, &vlan, ETH_ADDR_SCAN_ARGS(mac), &age)
520             != 2 + ETH_ADDR_SCAN_COUNT + 1) {
521             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 1);
522             VLOG_INFO_RL(&rl, "fdb/show output has invalid format: %s", line);
523             continue;
524         }
525
526         if (vlan != br_vlan) {
527             continue;
528         }
529
530         if (skip > 0) {
531             skip--;
532             continue;
533         }
534
535         /* Is this the MAC address of an interface on the bridge? */
536         is_local = false;
537         for (i = 0; i < n_local_macs; i++) {
538             if (eth_addr_equals(local_macs[i].addr, mac)) {
539                 is_local = true;
540                 break;
541             }
542         }
543
544         entry = ofpbuf_put_uninit(&query_data, sizeof *entry);
545         memcpy(entry->mac_addr, mac, ETH_ADDR_LEN);
546         entry->port_no = port & 0xff;
547         entry->is_local = is_local;
548         entry->ageing_timer_value = age * HZ;
549         entry->port_hi = (port & 0xff00) >> 8;
550         entry->pad0 = 0;
551         entry->unused = 0;
552         count--;
553     }
554     free(output);
555
556     /* Compose and send reply to datapath. */
557     reply = compose_reply(seq, 0);
558     nl_msg_put_unspec(reply, BRC_GENL_A_FDB_DATA,
559                       query_data.data, query_data.size);
560     send_reply(reply);
561
562     /* Free memory. */
563     ofpbuf_uninit(&query_data);
564     free(local_macs);
565
566     return 0;
567 }
568
569 static void
570 send_ifindex_reply(uint32_t seq, char *output)
571 {
572     size_t allocated_indices;
573     char *save_ptr = NULL;
574     struct ofpbuf *reply;
575     const char *iface;
576     size_t n_indices;
577     int *indices;
578
579     indices = NULL;
580     n_indices = allocated_indices = 0;
581     for (iface = strtok_r(output, " \t\r\n", &save_ptr); iface;
582          iface = strtok_r(NULL, " \t\r\n", &save_ptr)) {
583         int ifindex;
584
585         if (n_indices >= allocated_indices) {
586             indices = x2nrealloc(indices, &allocated_indices, sizeof *indices);
587         }
588
589         ifindex = if_nametoindex(iface);
590         if (ifindex) {
591             indices[n_indices++] = ifindex;
592         }
593     }
594
595     /* Compose and send reply. */
596     reply = compose_reply(seq, 0);
597     nl_msg_put_unspec(reply, BRC_GENL_A_IFINDEXES,
598                       indices, n_indices * sizeof *indices);
599     send_reply(reply);
600
601     /* Free memory. */
602     free(indices);
603 }
604
605 static int
606 handle_get_bridges_cmd(struct ofpbuf *buffer)
607 {
608     char *output;
609     uint32_t seq;
610     int error;
611
612     /* Parse Netlink command.
613      *
614      * The command doesn't actually have any arguments, but we need the
615      * sequence number to send the reply. */
616     error = parse_command(buffer, &seq, NULL, NULL, NULL, NULL);
617     if (error) {
618         return error;
619     }
620
621     output = capture_vsctl(vsctl_program, VSCTL_OPTIONS, "list-br", (char *) NULL);
622     if (!output) {
623         return ENODEV;
624     }
625
626     send_ifindex_reply(seq, output);
627     free(output);
628     return 0;
629 }
630
631 static int
632 handle_get_ports_cmd(struct ofpbuf *buffer)
633 {
634     const char *linux_name;
635     uint32_t seq;
636     char *output;
637     int error;
638
639     /* Parse Netlink command. */
640     error = parse_command(buffer, &seq, &linux_name, NULL, NULL, NULL);
641     if (error) {
642         return error;
643     }
644
645     output = capture_vsctl(vsctl_program, VSCTL_OPTIONS, "list-ports", linux_name,
646                            (char *) NULL);
647     if (!output) {
648         return ENODEV;
649     }
650
651     send_ifindex_reply(seq, output);
652     free(output);
653     return 0;
654 }
655
656 static struct ofpbuf *
657 brc_recv_update__(void)
658 {
659     for (;;) {
660         struct ofpbuf *buffer;
661         int retval;
662
663         retval = nl_sock_recv(brc_sock, &buffer, false);
664         switch (retval) {
665         case 0:
666             if (nl_msg_nlmsgerr(buffer, NULL)
667                 || nl_msg_nlmsghdr(buffer)->nlmsg_type == NLMSG_DONE) {
668                 break;
669             }
670             return buffer;
671
672         case ENOBUFS:
673             break;
674
675         case EAGAIN:
676             return NULL;
677
678         default:
679             VLOG_WARN_RL(&rl, "brc_recv_update: %s", strerror(retval));
680             return NULL;
681         }
682         ofpbuf_delete(buffer);
683     }
684 }
685
686 static void
687 brc_recv_update(void)
688 {
689     struct ofpbuf *buffer;
690     struct genlmsghdr *genlmsghdr;
691
692     buffer = brc_recv_update__();
693     if (!buffer) {
694         return;
695     }
696
697     genlmsghdr = nl_msg_genlmsghdr(buffer);
698     if (!genlmsghdr) {
699         VLOG_WARN_RL(&rl, "received packet too short for generic NetLink");
700         goto error;
701     }
702
703     if (nl_msg_nlmsghdr(buffer)->nlmsg_type != brc_family) {
704         VLOG_DBG_RL(&rl, "received type (%"PRIu16") != brcompat family (%d)",
705                 nl_msg_nlmsghdr(buffer)->nlmsg_type, brc_family);
706         goto error;
707     }
708
709     /* Service all pending network device notifications before executing the
710      * command.  This is very important to avoid a race in a scenario like the
711      * following, which is what happens with XenServer Tools version 5.0.0
712      * during boot of a Windows VM:
713      *
714      *      1. Create tap1.0 and vif1.0.
715      *      2. Delete tap1.0.
716      *      3. Delete vif1.0.
717      *      4. Re-create vif1.0.
718      *
719      * We must process the network device notification from step 3 before we
720      * process the brctl command from step 4.  If we process them in the
721      * reverse order, then step 4 completes as a no-op but step 3 then deletes
722      * the port that was just added.
723      *
724      * (XenServer Tools 5.5.0 does not exhibit this behavior, and neither does
725      * a VM without Tools installed at all.)
726      */
727     rtnetlink_link_notifier_run();
728
729     switch (genlmsghdr->cmd) {
730     case BRC_GENL_C_DP_ADD:
731         handle_bridge_cmd(buffer, true);
732         break;
733
734     case BRC_GENL_C_DP_DEL:
735         handle_bridge_cmd(buffer, false);
736         break;
737
738     case BRC_GENL_C_PORT_ADD:
739         handle_port_cmd(buffer, true);
740         break;
741
742     case BRC_GENL_C_PORT_DEL:
743         handle_port_cmd(buffer, false);
744         break;
745
746     case BRC_GENL_C_FDB_QUERY:
747         handle_fdb_query_cmd(buffer);
748         break;
749
750     case BRC_GENL_C_GET_BRIDGES:
751         handle_get_bridges_cmd(buffer);
752         break;
753
754     case BRC_GENL_C_GET_PORTS:
755         handle_get_ports_cmd(buffer);
756         break;
757
758     default:
759         VLOG_WARN_RL(&rl, "received unknown brc netlink command: %d\n",
760                      genlmsghdr->cmd);
761         break;
762     }
763
764 error:
765     ofpbuf_delete(buffer);
766 }
767
768 static void
769 netdev_changed_cb(const struct rtnetlink_link_change *change,
770                   void *aux OVS_UNUSED)
771 {
772     char br_name[IFNAMSIZ];
773     const char *port_name;
774
775     if (!change) {
776         VLOG_WARN_RL(&rl, "network monitor socket overflowed");
777         return;
778     }
779
780     if (change->nlmsg_type != RTM_DELLINK || !change->master_ifindex) {
781         return;
782     }
783
784     port_name = change->ifname;
785     if (!if_indextoname(change->master_ifindex, br_name)) {
786         return;
787     }
788
789     VLOG_INFO("network device %s destroyed, removing from bridge %s",
790               port_name, br_name);
791
792     run_vsctl(vsctl_program, VSCTL_OPTIONS,
793               "--", "--if-exists", "del-port", br_name, port_name,
794               "--", "comment", "ovs-brcompatd:", port_name, "disappeared",
795               (char *) NULL);
796 }
797
798 int
799 main(int argc, char *argv[])
800 {
801     extern struct vlog_module VLM_reconnect;
802     struct rtnetlink_notifier link_notifier;
803     struct unixctl_server *unixctl;
804     int retval;
805
806     proctitle_init(argc, argv);
807     set_program_name(argv[0]);
808     vlog_set_levels(&VLM_reconnect, VLF_ANY_FACILITY, VLL_WARN);
809
810     parse_options(argc, argv);
811     signal(SIGPIPE, SIG_IGN);
812     process_init();
813
814     daemonize_start();
815
816     retval = unixctl_server_create(NULL, &unixctl);
817     if (retval) {
818         exit(EXIT_FAILURE);
819     }
820
821     if (brc_open(&brc_sock)) {
822         VLOG_FATAL("could not open brcompat socket.  Check "
823                    "\"brcompat\" kernel module.");
824     }
825
826
827     rtnetlink_link_notifier_register(&link_notifier, netdev_changed_cb, NULL);
828
829     daemonize_complete();
830
831     for (;;) {
832         unixctl_server_run(unixctl);
833         rtnetlink_link_notifier_run();
834         brc_recv_update();
835
836         netdev_run();
837
838         nl_sock_wait(brc_sock, POLLIN);
839         unixctl_server_wait(unixctl);
840         rtnetlink_link_notifier_wait();
841         netdev_wait();
842         poll_block();
843     }
844
845     rtnetlink_link_notifier_unregister(&link_notifier);
846
847     return 0;
848 }
849
850 static void
851 parse_options(int argc, char *argv[])
852 {
853     enum {
854         OPT_APPCTL,
855         OPT_VSCTL,
856         VLOG_OPTION_ENUMS,
857         LEAK_CHECKER_OPTION_ENUMS,
858         DAEMON_OPTION_ENUMS
859     };
860     static struct option long_options[] = {
861         {"help",             no_argument, NULL, 'h'},
862         {"version",          no_argument, NULL, 'V'},
863         {"appctl",           required_argument, NULL, OPT_APPCTL},
864         {"vsctl",            required_argument, NULL, OPT_VSCTL},
865         DAEMON_LONG_OPTIONS,
866         VLOG_LONG_OPTIONS,
867         LEAK_CHECKER_LONG_OPTIONS,
868         {NULL, 0, NULL, 0},
869     };
870     char *short_options = long_options_to_short_options(long_options);
871     const char *appctl = "ovs-appctl";
872     const char *vsctl = "ovs-vsctl";
873
874     for (;;) {
875         int c;
876
877         c = getopt_long(argc, argv, short_options, long_options, NULL);
878         if (c == -1) {
879             break;
880         }
881
882         switch (c) {
883         case 'H':
884         case 'h':
885             usage();
886
887         case 'V':
888             ovs_print_version(0, 0);
889             exit(EXIT_SUCCESS);
890
891         case OPT_APPCTL:
892             appctl = optarg;
893             break;
894
895         case OPT_VSCTL:
896             vsctl = optarg;
897             break;
898
899         VLOG_OPTION_HANDLERS
900         DAEMON_OPTION_HANDLERS
901         LEAK_CHECKER_OPTION_HANDLERS
902
903         case '?':
904             exit(EXIT_FAILURE);
905
906         default:
907             abort();
908         }
909     }
910     free(short_options);
911
912     appctl_program = process_search_path(appctl);
913     if (!appctl_program) {
914         VLOG_FATAL("%s: not found in $PATH (use --appctl to specify an "
915                    "alternate location)", appctl);
916     }
917
918     vsctl_program = process_search_path(vsctl);
919     if (!vsctl_program) {
920         VLOG_FATAL("%s: not found in $PATH (use --vsctl to specify an "
921                    "alternate location)", vsctl);
922     }
923
924     if (argc != optind) {
925         VLOG_FATAL("no non-option arguments are supported; "
926                    "use --help for usage");
927     }
928 }
929
930 static void
931 usage(void)
932 {
933     printf("%s: bridge compatibility front-end for ovs-vswitchd\n"
934            "usage: %s [OPTIONS]\n",
935            program_name, program_name);
936     printf("\nConfiguration options:\n"
937            "  --appctl=PROGRAM        overrides $PATH for finding ovs-appctl\n"
938            "  --vsctl=PROGRAM         overrides $PATH for finding ovs-vsctl\n"
939           );
940     daemon_usage();
941     vlog_usage();
942     printf("\nOther options:\n"
943            "  -h, --help              display this help message\n"
944            "  -V, --version           display version information\n");
945     leak_checker_usage();
946     exit(EXIT_SUCCESS);
947 }