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