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