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