ipvs: Initialize mcast addr at compile time
[linux-2.6] / net / ipv4 / ipvs / ip_vs_sync.c
1 /*
2  * IPVS         An implementation of the IP virtual server support for the
3  *              LINUX operating system.  IPVS is now implemented as a module
4  *              over the NetFilter framework. IPVS can be used to build a
5  *              high-performance and highly available server based on a
6  *              cluster of servers.
7  *
8  * Authors:     Wensong Zhang <wensong@linuxvirtualserver.org>
9  *
10  * ip_vs_sync:  sync connection info from master load balancer to backups
11  *              through multicast
12  *
13  * Changes:
14  *      Alexandre Cassen        :       Added master & backup support at a time.
15  *      Alexandre Cassen        :       Added SyncID support for incoming sync
16  *                                      messages filtering.
17  *      Justin Ossevoort        :       Fix endian problem on sync message size.
18  */
19
20 #include <linux/module.h>
21 #include <linux/slab.h>
22 #include <linux/inetdevice.h>
23 #include <linux/net.h>
24 #include <linux/completion.h>
25 #include <linux/delay.h>
26 #include <linux/skbuff.h>
27 #include <linux/in.h>
28 #include <linux/igmp.h>                 /* for ip_mc_join_group */
29 #include <linux/udp.h>
30
31 #include <net/ip.h>
32 #include <net/sock.h>
33 #include <asm/uaccess.h>                /* for get_fs and set_fs */
34
35 #include <net/ip_vs.h>
36
37 #define IP_VS_SYNC_GROUP 0xe0000051    /* multicast addr - 224.0.0.81 */
38 #define IP_VS_SYNC_PORT  8848          /* multicast port */
39
40
41 /*
42  *      IPVS sync connection entry
43  */
44 struct ip_vs_sync_conn {
45         __u8                    reserved;
46
47         /* Protocol, addresses and port numbers */
48         __u8                    protocol;       /* Which protocol (TCP/UDP) */
49         __be16                  cport;
50         __be16                  vport;
51         __be16                  dport;
52         __be32                  caddr;          /* client address */
53         __be32                  vaddr;          /* virtual address */
54         __be32                  daddr;          /* destination address */
55
56         /* Flags and state transition */
57         __be16                  flags;          /* status flags */
58         __be16                  state;          /* state info */
59
60         /* The sequence options start here */
61 };
62
63 struct ip_vs_sync_conn_options {
64         struct ip_vs_seq        in_seq;         /* incoming seq. struct */
65         struct ip_vs_seq        out_seq;        /* outgoing seq. struct */
66 };
67
68 struct ip_vs_sync_thread_data {
69         struct completion *startup;
70         int state;
71 };
72
73 #define SIMPLE_CONN_SIZE  (sizeof(struct ip_vs_sync_conn))
74 #define FULL_CONN_SIZE  \
75 (sizeof(struct ip_vs_sync_conn) + sizeof(struct ip_vs_sync_conn_options))
76
77
78 /*
79   The master mulitcasts messages to the backup load balancers in the
80   following format.
81
82        0                   1                   2                   3
83        0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
84       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
85       |  Count Conns  |    SyncID     |            Size               |
86       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
87       |                                                               |
88       |                    IPVS Sync Connection (1)                   |
89       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
90       |                            .                                  |
91       |                            .                                  |
92       |                            .                                  |
93       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
94       |                                                               |
95       |                    IPVS Sync Connection (n)                   |
96       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
97 */
98
99 #define SYNC_MESG_HEADER_LEN    4
100
101 struct ip_vs_sync_mesg {
102         __u8                    nr_conns;
103         __u8                    syncid;
104         __u16                   size;
105
106         /* ip_vs_sync_conn entries start here */
107 };
108
109 /* the maximum length of sync (sending/receiving) message */
110 static int sync_send_mesg_maxlen;
111 static int sync_recv_mesg_maxlen;
112
113 struct ip_vs_sync_buff {
114         struct list_head        list;
115         unsigned long           firstuse;
116
117         /* pointers for the message data */
118         struct ip_vs_sync_mesg  *mesg;
119         unsigned char           *head;
120         unsigned char           *end;
121 };
122
123
124 /* the sync_buff list head and the lock */
125 static LIST_HEAD(ip_vs_sync_queue);
126 static DEFINE_SPINLOCK(ip_vs_sync_lock);
127
128 /* current sync_buff for accepting new conn entries */
129 static struct ip_vs_sync_buff   *curr_sb = NULL;
130 static DEFINE_SPINLOCK(curr_sb_lock);
131
132 /* ipvs sync daemon state */
133 volatile int ip_vs_sync_state = IP_VS_STATE_NONE;
134 volatile int ip_vs_master_syncid = 0;
135 volatile int ip_vs_backup_syncid = 0;
136
137 /* multicast interface name */
138 char ip_vs_master_mcast_ifn[IP_VS_IFNAME_MAXLEN];
139 char ip_vs_backup_mcast_ifn[IP_VS_IFNAME_MAXLEN];
140
141 /* multicast addr */
142 static struct sockaddr_in mcast_addr = {
143         .sin_family             = AF_INET,
144         .sin_port               = __constant_htons(IP_VS_SYNC_PORT),
145         .sin_addr.s_addr        = __constant_htonl(IP_VS_SYNC_GROUP),
146 };
147
148
149 static inline void sb_queue_tail(struct ip_vs_sync_buff *sb)
150 {
151         spin_lock(&ip_vs_sync_lock);
152         list_add_tail(&sb->list, &ip_vs_sync_queue);
153         spin_unlock(&ip_vs_sync_lock);
154 }
155
156 static inline struct ip_vs_sync_buff * sb_dequeue(void)
157 {
158         struct ip_vs_sync_buff *sb;
159
160         spin_lock_bh(&ip_vs_sync_lock);
161         if (list_empty(&ip_vs_sync_queue)) {
162                 sb = NULL;
163         } else {
164                 sb = list_entry(ip_vs_sync_queue.next,
165                                 struct ip_vs_sync_buff,
166                                 list);
167                 list_del(&sb->list);
168         }
169         spin_unlock_bh(&ip_vs_sync_lock);
170
171         return sb;
172 }
173
174 static inline struct ip_vs_sync_buff * ip_vs_sync_buff_create(void)
175 {
176         struct ip_vs_sync_buff *sb;
177
178         if (!(sb=kmalloc(sizeof(struct ip_vs_sync_buff), GFP_ATOMIC)))
179                 return NULL;
180
181         if (!(sb->mesg=kmalloc(sync_send_mesg_maxlen, GFP_ATOMIC))) {
182                 kfree(sb);
183                 return NULL;
184         }
185         sb->mesg->nr_conns = 0;
186         sb->mesg->syncid = ip_vs_master_syncid;
187         sb->mesg->size = 4;
188         sb->head = (unsigned char *)sb->mesg + 4;
189         sb->end = (unsigned char *)sb->mesg + sync_send_mesg_maxlen;
190         sb->firstuse = jiffies;
191         return sb;
192 }
193
194 static inline void ip_vs_sync_buff_release(struct ip_vs_sync_buff *sb)
195 {
196         kfree(sb->mesg);
197         kfree(sb);
198 }
199
200 /*
201  *      Get the current sync buffer if it has been created for more
202  *      than the specified time or the specified time is zero.
203  */
204 static inline struct ip_vs_sync_buff *
205 get_curr_sync_buff(unsigned long time)
206 {
207         struct ip_vs_sync_buff *sb;
208
209         spin_lock_bh(&curr_sb_lock);
210         if (curr_sb && (time == 0 ||
211                         time_before(jiffies - curr_sb->firstuse, time))) {
212                 sb = curr_sb;
213                 curr_sb = NULL;
214         } else
215                 sb = NULL;
216         spin_unlock_bh(&curr_sb_lock);
217         return sb;
218 }
219
220
221 /*
222  *      Add an ip_vs_conn information into the current sync_buff.
223  *      Called by ip_vs_in.
224  */
225 void ip_vs_sync_conn(struct ip_vs_conn *cp)
226 {
227         struct ip_vs_sync_mesg *m;
228         struct ip_vs_sync_conn *s;
229         int len;
230
231         spin_lock(&curr_sb_lock);
232         if (!curr_sb) {
233                 if (!(curr_sb=ip_vs_sync_buff_create())) {
234                         spin_unlock(&curr_sb_lock);
235                         IP_VS_ERR("ip_vs_sync_buff_create failed.\n");
236                         return;
237                 }
238         }
239
240         len = (cp->flags & IP_VS_CONN_F_SEQ_MASK) ? FULL_CONN_SIZE :
241                 SIMPLE_CONN_SIZE;
242         m = curr_sb->mesg;
243         s = (struct ip_vs_sync_conn *)curr_sb->head;
244
245         /* copy members */
246         s->protocol = cp->protocol;
247         s->cport = cp->cport;
248         s->vport = cp->vport;
249         s->dport = cp->dport;
250         s->caddr = cp->caddr;
251         s->vaddr = cp->vaddr;
252         s->daddr = cp->daddr;
253         s->flags = htons(cp->flags & ~IP_VS_CONN_F_HASHED);
254         s->state = htons(cp->state);
255         if (cp->flags & IP_VS_CONN_F_SEQ_MASK) {
256                 struct ip_vs_sync_conn_options *opt =
257                         (struct ip_vs_sync_conn_options *)&s[1];
258                 memcpy(opt, &cp->in_seq, sizeof(*opt));
259         }
260
261         m->nr_conns++;
262         m->size += len;
263         curr_sb->head += len;
264
265         /* check if there is a space for next one */
266         if (curr_sb->head+FULL_CONN_SIZE > curr_sb->end) {
267                 sb_queue_tail(curr_sb);
268                 curr_sb = NULL;
269         }
270         spin_unlock(&curr_sb_lock);
271
272         /* synchronize its controller if it has */
273         if (cp->control)
274                 ip_vs_sync_conn(cp->control);
275 }
276
277
278 /*
279  *      Process received multicast message and create the corresponding
280  *      ip_vs_conn entries.
281  */
282 static void ip_vs_process_message(const char *buffer, const size_t buflen)
283 {
284         struct ip_vs_sync_mesg *m = (struct ip_vs_sync_mesg *)buffer;
285         struct ip_vs_sync_conn *s;
286         struct ip_vs_sync_conn_options *opt;
287         struct ip_vs_conn *cp;
288         struct ip_vs_protocol *pp;
289         struct ip_vs_dest *dest;
290         char *p;
291         int i;
292
293         if (buflen < sizeof(struct ip_vs_sync_mesg)) {
294                 IP_VS_ERR_RL("sync message header too short\n");
295                 return;
296         }
297
298         /* Convert size back to host byte order */
299         m->size = ntohs(m->size);
300
301         if (buflen != m->size) {
302                 IP_VS_ERR_RL("bogus sync message size\n");
303                 return;
304         }
305
306         /* SyncID sanity check */
307         if (ip_vs_backup_syncid != 0 && m->syncid != ip_vs_backup_syncid) {
308                 IP_VS_DBG(7, "Ignoring incoming msg with syncid = %d\n",
309                           m->syncid);
310                 return;
311         }
312
313         p = (char *)buffer + sizeof(struct ip_vs_sync_mesg);
314         for (i=0; i<m->nr_conns; i++) {
315                 unsigned flags, state;
316
317                 if (p + SIMPLE_CONN_SIZE > buffer+buflen) {
318                         IP_VS_ERR_RL("bogus conn in sync message\n");
319                         return;
320                 }
321                 s = (struct ip_vs_sync_conn *) p;
322                 flags = ntohs(s->flags) | IP_VS_CONN_F_SYNC;
323                 flags &= ~IP_VS_CONN_F_HASHED;
324                 if (flags & IP_VS_CONN_F_SEQ_MASK) {
325                         opt = (struct ip_vs_sync_conn_options *)&s[1];
326                         p += FULL_CONN_SIZE;
327                         if (p > buffer+buflen) {
328                                 IP_VS_ERR_RL("bogus conn options in sync message\n");
329                                 return;
330                         }
331                 } else {
332                         opt = NULL;
333                         p += SIMPLE_CONN_SIZE;
334                 }
335
336                 state = ntohs(s->state);
337                 if (!(flags & IP_VS_CONN_F_TEMPLATE)) {
338                         pp = ip_vs_proto_get(s->protocol);
339                         if (!pp) {
340                                 IP_VS_ERR_RL("Unsupported protocol %u in sync msg\n",
341                                         s->protocol);
342                                 continue;
343                         }
344                         if (state >= pp->num_states) {
345                                 IP_VS_DBG(2, "Invalid %s state %u in sync msg\n",
346                                         pp->name, state);
347                                 continue;
348                         }
349                 } else {
350                         /* protocol in templates is not used for state/timeout */
351                         pp = NULL;
352                         if (state > 0) {
353                                 IP_VS_DBG(2, "Invalid template state %u in sync msg\n",
354                                         state);
355                                 state = 0;
356                         }
357                 }
358
359                 if (!(flags & IP_VS_CONN_F_TEMPLATE))
360                         cp = ip_vs_conn_in_get(s->protocol,
361                                                s->caddr, s->cport,
362                                                s->vaddr, s->vport);
363                 else
364                         cp = ip_vs_ct_in_get(s->protocol,
365                                                s->caddr, s->cport,
366                                                s->vaddr, s->vport);
367                 if (!cp) {
368                         /*
369                          * Find the appropriate destination for the connection.
370                          * If it is not found the connection will remain unbound
371                          * but still handled.
372                          */
373                         dest = ip_vs_find_dest(s->daddr, s->dport,
374                                                s->vaddr, s->vport,
375                                                s->protocol);
376                         /*  Set the approprite ativity flag */
377                         if (s->protocol == IPPROTO_TCP) {
378                                 if (state != IP_VS_TCP_S_ESTABLISHED)
379                                         flags |= IP_VS_CONN_F_INACTIVE;
380                                 else
381                                         flags &= ~IP_VS_CONN_F_INACTIVE;
382                         }
383                         cp = ip_vs_conn_new(s->protocol,
384                                             s->caddr, s->cport,
385                                             s->vaddr, s->vport,
386                                             s->daddr, s->dport,
387                                             flags, dest);
388                         if (dest)
389                                 atomic_dec(&dest->refcnt);
390                         if (!cp) {
391                                 IP_VS_ERR("ip_vs_conn_new failed\n");
392                                 return;
393                         }
394                 } else if (!cp->dest) {
395                         dest = ip_vs_try_bind_dest(cp);
396                         if (dest)
397                                 atomic_dec(&dest->refcnt);
398                 } else if ((cp->dest) && (cp->protocol == IPPROTO_TCP) &&
399                            (cp->state != state)) {
400                         /* update active/inactive flag for the connection */
401                         dest = cp->dest;
402                         if (!(cp->flags & IP_VS_CONN_F_INACTIVE) &&
403                                 (state != IP_VS_TCP_S_ESTABLISHED)) {
404                                 atomic_dec(&dest->activeconns);
405                                 atomic_inc(&dest->inactconns);
406                                 cp->flags |= IP_VS_CONN_F_INACTIVE;
407                         } else if ((cp->flags & IP_VS_CONN_F_INACTIVE) &&
408                                 (state == IP_VS_TCP_S_ESTABLISHED)) {
409                                 atomic_inc(&dest->activeconns);
410                                 atomic_dec(&dest->inactconns);
411                                 cp->flags &= ~IP_VS_CONN_F_INACTIVE;
412                         }
413                 }
414
415                 if (opt)
416                         memcpy(&cp->in_seq, opt, sizeof(*opt));
417                 atomic_set(&cp->in_pkts, sysctl_ip_vs_sync_threshold[0]);
418                 cp->state = state;
419                 cp->old_state = cp->state;
420                 /*
421                  * We can not recover the right timeout for templates
422                  * in all cases, we can not find the right fwmark
423                  * virtual service. If needed, we can do it for
424                  * non-fwmark persistent services.
425                  */
426                 if (!(flags & IP_VS_CONN_F_TEMPLATE) && pp->timeout_table)
427                         cp->timeout = pp->timeout_table[state];
428                 else
429                         cp->timeout = (3*60*HZ);
430                 ip_vs_conn_put(cp);
431         }
432 }
433
434
435 /*
436  *      Setup loopback of outgoing multicasts on a sending socket
437  */
438 static void set_mcast_loop(struct sock *sk, u_char loop)
439 {
440         struct inet_sock *inet = inet_sk(sk);
441
442         /* setsockopt(sock, SOL_IP, IP_MULTICAST_LOOP, &loop, sizeof(loop)); */
443         lock_sock(sk);
444         inet->mc_loop = loop ? 1 : 0;
445         release_sock(sk);
446 }
447
448 /*
449  *      Specify TTL for outgoing multicasts on a sending socket
450  */
451 static void set_mcast_ttl(struct sock *sk, u_char ttl)
452 {
453         struct inet_sock *inet = inet_sk(sk);
454
455         /* setsockopt(sock, SOL_IP, IP_MULTICAST_TTL, &ttl, sizeof(ttl)); */
456         lock_sock(sk);
457         inet->mc_ttl = ttl;
458         release_sock(sk);
459 }
460
461 /*
462  *      Specifiy default interface for outgoing multicasts
463  */
464 static int set_mcast_if(struct sock *sk, char *ifname)
465 {
466         struct net_device *dev;
467         struct inet_sock *inet = inet_sk(sk);
468
469         if ((dev = __dev_get_by_name(&init_net, ifname)) == NULL)
470                 return -ENODEV;
471
472         if (sk->sk_bound_dev_if && dev->ifindex != sk->sk_bound_dev_if)
473                 return -EINVAL;
474
475         lock_sock(sk);
476         inet->mc_index = dev->ifindex;
477         /*  inet->mc_addr  = 0; */
478         release_sock(sk);
479
480         return 0;
481 }
482
483
484 /*
485  *      Set the maximum length of sync message according to the
486  *      specified interface's MTU.
487  */
488 static int set_sync_mesg_maxlen(int sync_state)
489 {
490         struct net_device *dev;
491         int num;
492
493         if (sync_state == IP_VS_STATE_MASTER) {
494                 if ((dev = __dev_get_by_name(&init_net, ip_vs_master_mcast_ifn)) == NULL)
495                         return -ENODEV;
496
497                 num = (dev->mtu - sizeof(struct iphdr) -
498                        sizeof(struct udphdr) -
499                        SYNC_MESG_HEADER_LEN - 20) / SIMPLE_CONN_SIZE;
500                 sync_send_mesg_maxlen =
501                         SYNC_MESG_HEADER_LEN + SIMPLE_CONN_SIZE * num;
502                 IP_VS_DBG(7, "setting the maximum length of sync sending "
503                           "message %d.\n", sync_send_mesg_maxlen);
504         } else if (sync_state == IP_VS_STATE_BACKUP) {
505                 if ((dev = __dev_get_by_name(&init_net, ip_vs_backup_mcast_ifn)) == NULL)
506                         return -ENODEV;
507
508                 sync_recv_mesg_maxlen = dev->mtu -
509                         sizeof(struct iphdr) - sizeof(struct udphdr);
510                 IP_VS_DBG(7, "setting the maximum length of sync receiving "
511                           "message %d.\n", sync_recv_mesg_maxlen);
512         }
513
514         return 0;
515 }
516
517
518 /*
519  *      Join a multicast group.
520  *      the group is specified by a class D multicast address 224.0.0.0/8
521  *      in the in_addr structure passed in as a parameter.
522  */
523 static int
524 join_mcast_group(struct sock *sk, struct in_addr *addr, char *ifname)
525 {
526         struct ip_mreqn mreq;
527         struct net_device *dev;
528         int ret;
529
530         memset(&mreq, 0, sizeof(mreq));
531         memcpy(&mreq.imr_multiaddr, addr, sizeof(struct in_addr));
532
533         if ((dev = __dev_get_by_name(&init_net, ifname)) == NULL)
534                 return -ENODEV;
535         if (sk->sk_bound_dev_if && dev->ifindex != sk->sk_bound_dev_if)
536                 return -EINVAL;
537
538         mreq.imr_ifindex = dev->ifindex;
539
540         lock_sock(sk);
541         ret = ip_mc_join_group(sk, &mreq);
542         release_sock(sk);
543
544         return ret;
545 }
546
547
548 static int bind_mcastif_addr(struct socket *sock, char *ifname)
549 {
550         struct net_device *dev;
551         __be32 addr;
552         struct sockaddr_in sin;
553
554         if ((dev = __dev_get_by_name(&init_net, ifname)) == NULL)
555                 return -ENODEV;
556
557         addr = inet_select_addr(dev, 0, RT_SCOPE_UNIVERSE);
558         if (!addr)
559                 IP_VS_ERR("You probably need to specify IP address on "
560                           "multicast interface.\n");
561
562         IP_VS_DBG(7, "binding socket with (%s) %u.%u.%u.%u\n",
563                   ifname, NIPQUAD(addr));
564
565         /* Now bind the socket with the address of multicast interface */
566         sin.sin_family       = AF_INET;
567         sin.sin_addr.s_addr  = addr;
568         sin.sin_port         = 0;
569
570         return sock->ops->bind(sock, (struct sockaddr*)&sin, sizeof(sin));
571 }
572
573 /*
574  *      Set up sending multicast socket over UDP
575  */
576 static struct socket * make_send_sock(void)
577 {
578         struct socket *sock;
579
580         /* First create a socket */
581         if (sock_create_kern(PF_INET, SOCK_DGRAM, IPPROTO_UDP, &sock) < 0) {
582                 IP_VS_ERR("Error during creation of socket; terminating\n");
583                 return NULL;
584         }
585
586         if (set_mcast_if(sock->sk, ip_vs_master_mcast_ifn) < 0) {
587                 IP_VS_ERR("Error setting outbound mcast interface\n");
588                 goto error;
589         }
590
591         set_mcast_loop(sock->sk, 0);
592         set_mcast_ttl(sock->sk, 1);
593
594         if (bind_mcastif_addr(sock, ip_vs_master_mcast_ifn) < 0) {
595                 IP_VS_ERR("Error binding address of the mcast interface\n");
596                 goto error;
597         }
598
599         if (sock->ops->connect(sock,
600                                (struct sockaddr*)&mcast_addr,
601                                sizeof(struct sockaddr), 0) < 0) {
602                 IP_VS_ERR("Error connecting to the multicast addr\n");
603                 goto error;
604         }
605
606         return sock;
607
608   error:
609         sock_release(sock);
610         return NULL;
611 }
612
613
614 /*
615  *      Set up receiving multicast socket over UDP
616  */
617 static struct socket * make_receive_sock(void)
618 {
619         struct socket *sock;
620
621         /* First create a socket */
622         if (sock_create_kern(PF_INET, SOCK_DGRAM, IPPROTO_UDP, &sock) < 0) {
623                 IP_VS_ERR("Error during creation of socket; terminating\n");
624                 return NULL;
625         }
626
627         /* it is equivalent to the REUSEADDR option in user-space */
628         sock->sk->sk_reuse = 1;
629
630         if (sock->ops->bind(sock,
631                             (struct sockaddr*)&mcast_addr,
632                             sizeof(struct sockaddr)) < 0) {
633                 IP_VS_ERR("Error binding to the multicast addr\n");
634                 goto error;
635         }
636
637         /* join the multicast group */
638         if (join_mcast_group(sock->sk,
639                              (struct in_addr*)&mcast_addr.sin_addr,
640                              ip_vs_backup_mcast_ifn) < 0) {
641                 IP_VS_ERR("Error joining to the multicast group\n");
642                 goto error;
643         }
644
645         return sock;
646
647   error:
648         sock_release(sock);
649         return NULL;
650 }
651
652
653 static int
654 ip_vs_send_async(struct socket *sock, const char *buffer, const size_t length)
655 {
656         struct msghdr   msg = {.msg_flags = MSG_DONTWAIT|MSG_NOSIGNAL};
657         struct kvec     iov;
658         int             len;
659
660         EnterFunction(7);
661         iov.iov_base     = (void *)buffer;
662         iov.iov_len      = length;
663
664         len = kernel_sendmsg(sock, &msg, &iov, 1, (size_t)(length));
665
666         LeaveFunction(7);
667         return len;
668 }
669
670 static void
671 ip_vs_send_sync_msg(struct socket *sock, struct ip_vs_sync_mesg *msg)
672 {
673         int msize;
674
675         msize = msg->size;
676
677         /* Put size in network byte order */
678         msg->size = htons(msg->size);
679
680         if (ip_vs_send_async(sock, (char *)msg, msize) != msize)
681                 IP_VS_ERR("ip_vs_send_async error\n");
682 }
683
684 static int
685 ip_vs_receive(struct socket *sock, char *buffer, const size_t buflen)
686 {
687         struct msghdr           msg = {NULL,};
688         struct kvec             iov;
689         int                     len;
690
691         EnterFunction(7);
692
693         /* Receive a packet */
694         iov.iov_base     = buffer;
695         iov.iov_len      = (size_t)buflen;
696
697         len = kernel_recvmsg(sock, &msg, &iov, 1, buflen, 0);
698
699         if (len < 0)
700                 return -1;
701
702         LeaveFunction(7);
703         return len;
704 }
705
706
707 static DECLARE_WAIT_QUEUE_HEAD(sync_wait);
708 static pid_t sync_master_pid = 0;
709 static pid_t sync_backup_pid = 0;
710
711 static DECLARE_WAIT_QUEUE_HEAD(stop_sync_wait);
712 static int stop_master_sync = 0;
713 static int stop_backup_sync = 0;
714
715 static void sync_master_loop(void)
716 {
717         struct socket *sock;
718         struct ip_vs_sync_buff *sb;
719
720         /* create the sending multicast socket */
721         sock = make_send_sock();
722         if (!sock)
723                 return;
724
725         IP_VS_INFO("sync thread started: state = MASTER, mcast_ifn = %s, "
726                    "syncid = %d\n",
727                    ip_vs_master_mcast_ifn, ip_vs_master_syncid);
728
729         for (;;) {
730                 while ((sb=sb_dequeue())) {
731                         ip_vs_send_sync_msg(sock, sb->mesg);
732                         ip_vs_sync_buff_release(sb);
733                 }
734
735                 /* check if entries stay in curr_sb for 2 seconds */
736                 if ((sb = get_curr_sync_buff(2*HZ))) {
737                         ip_vs_send_sync_msg(sock, sb->mesg);
738                         ip_vs_sync_buff_release(sb);
739                 }
740
741                 if (stop_master_sync)
742                         break;
743
744                 msleep_interruptible(1000);
745         }
746
747         /* clean up the sync_buff queue */
748         while ((sb=sb_dequeue())) {
749                 ip_vs_sync_buff_release(sb);
750         }
751
752         /* clean up the current sync_buff */
753         if ((sb = get_curr_sync_buff(0))) {
754                 ip_vs_sync_buff_release(sb);
755         }
756
757         /* release the sending multicast socket */
758         sock_release(sock);
759 }
760
761
762 static void sync_backup_loop(void)
763 {
764         struct socket *sock;
765         char *buf;
766         int len;
767
768         if (!(buf = kmalloc(sync_recv_mesg_maxlen, GFP_ATOMIC))) {
769                 IP_VS_ERR("sync_backup_loop: kmalloc error\n");
770                 return;
771         }
772
773         /* create the receiving multicast socket */
774         sock = make_receive_sock();
775         if (!sock)
776                 goto out;
777
778         IP_VS_INFO("sync thread started: state = BACKUP, mcast_ifn = %s, "
779                    "syncid = %d\n",
780                    ip_vs_backup_mcast_ifn, ip_vs_backup_syncid);
781
782         for (;;) {
783                 /* do you have data now? */
784                 while (!skb_queue_empty(&(sock->sk->sk_receive_queue))) {
785                         if ((len =
786                              ip_vs_receive(sock, buf,
787                                            sync_recv_mesg_maxlen)) <= 0) {
788                                 IP_VS_ERR("receiving message error\n");
789                                 break;
790                         }
791                         /* disable bottom half, because it accessed the data
792                            shared by softirq while getting/creating conns */
793                         local_bh_disable();
794                         ip_vs_process_message(buf, len);
795                         local_bh_enable();
796                 }
797
798                 if (stop_backup_sync)
799                         break;
800
801                 msleep_interruptible(1000);
802         }
803
804         /* release the sending multicast socket */
805         sock_release(sock);
806
807   out:
808         kfree(buf);
809 }
810
811
812 static void set_sync_pid(int sync_state, pid_t sync_pid)
813 {
814         if (sync_state == IP_VS_STATE_MASTER)
815                 sync_master_pid = sync_pid;
816         else if (sync_state == IP_VS_STATE_BACKUP)
817                 sync_backup_pid = sync_pid;
818 }
819
820 static void set_stop_sync(int sync_state, int set)
821 {
822         if (sync_state == IP_VS_STATE_MASTER)
823                 stop_master_sync = set;
824         else if (sync_state == IP_VS_STATE_BACKUP)
825                 stop_backup_sync = set;
826         else {
827                 stop_master_sync = set;
828                 stop_backup_sync = set;
829         }
830 }
831
832 static int sync_thread(void *startup)
833 {
834         DECLARE_WAITQUEUE(wait, current);
835         mm_segment_t oldmm;
836         int state;
837         const char *name;
838         struct ip_vs_sync_thread_data *tinfo = startup;
839
840         /* increase the module use count */
841         ip_vs_use_count_inc();
842
843         if (ip_vs_sync_state & IP_VS_STATE_MASTER && !sync_master_pid) {
844                 state = IP_VS_STATE_MASTER;
845                 name = "ipvs_syncmaster";
846         } else if (ip_vs_sync_state & IP_VS_STATE_BACKUP && !sync_backup_pid) {
847                 state = IP_VS_STATE_BACKUP;
848                 name = "ipvs_syncbackup";
849         } else {
850                 IP_VS_BUG();
851                 ip_vs_use_count_dec();
852                 return -EINVAL;
853         }
854
855         daemonize(name);
856
857         oldmm = get_fs();
858         set_fs(KERNEL_DS);
859
860         /* Block all signals */
861         spin_lock_irq(&current->sighand->siglock);
862         siginitsetinv(&current->blocked, 0);
863         recalc_sigpending();
864         spin_unlock_irq(&current->sighand->siglock);
865
866         /* set the maximum length of sync message */
867         set_sync_mesg_maxlen(state);
868
869         add_wait_queue(&sync_wait, &wait);
870
871         set_sync_pid(state, task_pid_nr(current));
872         complete(tinfo->startup);
873
874         /*
875          * once we call the completion queue above, we should
876          * null out that reference, since its allocated on the
877          * stack of the creating kernel thread
878          */
879         tinfo->startup = NULL;
880
881         /* processing master/backup loop here */
882         if (state == IP_VS_STATE_MASTER)
883                 sync_master_loop();
884         else if (state == IP_VS_STATE_BACKUP)
885                 sync_backup_loop();
886         else IP_VS_BUG();
887
888         remove_wait_queue(&sync_wait, &wait);
889
890         /* thread exits */
891
892         /*
893          * If we weren't explicitly stopped, then we
894          * exited in error, and should undo our state
895          */
896         if ((!stop_master_sync) && (!stop_backup_sync))
897                 ip_vs_sync_state -= tinfo->state;
898
899         set_sync_pid(state, 0);
900         IP_VS_INFO("sync thread stopped!\n");
901
902         set_fs(oldmm);
903
904         /* decrease the module use count */
905         ip_vs_use_count_dec();
906
907         set_stop_sync(state, 0);
908         wake_up(&stop_sync_wait);
909
910         /*
911          * we need to free the structure that was allocated
912          * for us in start_sync_thread
913          */
914         kfree(tinfo);
915         return 0;
916 }
917
918
919 static int fork_sync_thread(void *startup)
920 {
921         pid_t pid;
922
923         /* fork the sync thread here, then the parent process of the
924            sync thread is the init process after this thread exits. */
925   repeat:
926         if ((pid = kernel_thread(sync_thread, startup, 0)) < 0) {
927                 IP_VS_ERR("could not create sync_thread due to %d... "
928                           "retrying.\n", pid);
929                 msleep_interruptible(1000);
930                 goto repeat;
931         }
932
933         return 0;
934 }
935
936
937 int start_sync_thread(int state, char *mcast_ifn, __u8 syncid)
938 {
939         DECLARE_COMPLETION_ONSTACK(startup);
940         pid_t pid;
941         struct ip_vs_sync_thread_data *tinfo;
942
943         if ((state == IP_VS_STATE_MASTER && sync_master_pid) ||
944             (state == IP_VS_STATE_BACKUP && sync_backup_pid))
945                 return -EEXIST;
946
947         /*
948          * Note that tinfo will be freed in sync_thread on exit
949          */
950         tinfo = kmalloc(sizeof(struct ip_vs_sync_thread_data), GFP_KERNEL);
951         if (!tinfo)
952                 return -ENOMEM;
953
954         IP_VS_DBG(7, "%s: pid %d\n", __func__, task_pid_nr(current));
955         IP_VS_DBG(7, "Each ip_vs_sync_conn entry need %Zd bytes\n",
956                   sizeof(struct ip_vs_sync_conn));
957
958         ip_vs_sync_state |= state;
959         if (state == IP_VS_STATE_MASTER) {
960                 strlcpy(ip_vs_master_mcast_ifn, mcast_ifn,
961                         sizeof(ip_vs_master_mcast_ifn));
962                 ip_vs_master_syncid = syncid;
963         } else {
964                 strlcpy(ip_vs_backup_mcast_ifn, mcast_ifn,
965                         sizeof(ip_vs_backup_mcast_ifn));
966                 ip_vs_backup_syncid = syncid;
967         }
968
969         tinfo->state = state;
970         tinfo->startup = &startup;
971
972   repeat:
973         if ((pid = kernel_thread(fork_sync_thread, tinfo, 0)) < 0) {
974                 IP_VS_ERR("could not create fork_sync_thread due to %d... "
975                           "retrying.\n", pid);
976                 msleep_interruptible(1000);
977                 goto repeat;
978         }
979
980         wait_for_completion(&startup);
981
982         return 0;
983 }
984
985
986 int stop_sync_thread(int state)
987 {
988         DECLARE_WAITQUEUE(wait, current);
989
990         if ((state == IP_VS_STATE_MASTER && !sync_master_pid) ||
991             (state == IP_VS_STATE_BACKUP && !sync_backup_pid))
992                 return -ESRCH;
993
994         IP_VS_DBG(7, "%s: pid %d\n", __func__, task_pid_nr(current));
995         IP_VS_INFO("stopping sync thread %d ...\n",
996                    (state == IP_VS_STATE_MASTER) ?
997                    sync_master_pid : sync_backup_pid);
998
999         __set_current_state(TASK_UNINTERRUPTIBLE);
1000         add_wait_queue(&stop_sync_wait, &wait);
1001         set_stop_sync(state, 1);
1002         ip_vs_sync_state -= state;
1003         wake_up(&sync_wait);
1004         schedule();
1005         __set_current_state(TASK_RUNNING);
1006         remove_wait_queue(&stop_sync_wait, &wait);
1007
1008         /* Note: no need to reap the sync thread, because its parent
1009            process is the init process */
1010
1011         if ((state == IP_VS_STATE_MASTER && stop_master_sync) ||
1012             (state == IP_VS_STATE_BACKUP && stop_backup_sync))
1013                 IP_VS_BUG();
1014
1015         return 0;
1016 }