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