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