]> git.kernelconcepts.de Git - karo-tx-linux.git/blob - net/netfilter/ipvs/ip_vs_sync.c
Merge branch 'for-4.1' of git://git.kernel.org/pub/scm/linux/kernel/git/tj/cgroup
[karo-tx-linux.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  * Version 1,   is capable of handling both version 0 and 1 messages.
9  *              Version 0 is the plain old format.
10  *              Note Version 0 receivers will just drop Ver 1 messages.
11  *              Version 1 is capable of handle IPv6, Persistence data,
12  *              time-outs, and firewall marks.
13  *              In ver.1 "ip_vs_sync_conn_options" will be sent in netw. order.
14  *              Ver. 0 can be turned on by sysctl -w net.ipv4.vs.sync_version=0
15  *
16  * Definitions  Message: is a complete datagram
17  *              Sync_conn: is a part of a Message
18  *              Param Data is an option to a Sync_conn.
19  *
20  * Authors:     Wensong Zhang <wensong@linuxvirtualserver.org>
21  *
22  * ip_vs_sync:  sync connection info from master load balancer to backups
23  *              through multicast
24  *
25  * Changes:
26  *      Alexandre Cassen        :       Added master & backup support at a time.
27  *      Alexandre Cassen        :       Added SyncID support for incoming sync
28  *                                      messages filtering.
29  *      Justin Ossevoort        :       Fix endian problem on sync message size.
30  *      Hans Schillstrom        :       Added Version 1: i.e. IPv6,
31  *                                      Persistence support, fwmark and time-out.
32  */
33
34 #define KMSG_COMPONENT "IPVS"
35 #define pr_fmt(fmt) KMSG_COMPONENT ": " fmt
36
37 #include <linux/module.h>
38 #include <linux/slab.h>
39 #include <linux/inetdevice.h>
40 #include <linux/net.h>
41 #include <linux/completion.h>
42 #include <linux/delay.h>
43 #include <linux/skbuff.h>
44 #include <linux/in.h>
45 #include <linux/igmp.h>                 /* for ip_mc_join_group */
46 #include <linux/udp.h>
47 #include <linux/err.h>
48 #include <linux/kthread.h>
49 #include <linux/wait.h>
50 #include <linux/kernel.h>
51
52 #include <asm/unaligned.h>              /* Used for ntoh_seq and hton_seq */
53
54 #include <net/ip.h>
55 #include <net/sock.h>
56
57 #include <net/ip_vs.h>
58
59 #define IP_VS_SYNC_GROUP 0xe0000051    /* multicast addr - 224.0.0.81 */
60 #define IP_VS_SYNC_PORT  8848          /* multicast port */
61
62 #define SYNC_PROTO_VER  1               /* Protocol version in header */
63
64 static struct lock_class_key __ipvs_sync_key;
65 /*
66  *      IPVS sync connection entry
67  *      Version 0, i.e. original version.
68  */
69 struct ip_vs_sync_conn_v0 {
70         __u8                    reserved;
71
72         /* Protocol, addresses and port numbers */
73         __u8                    protocol;       /* Which protocol (TCP/UDP) */
74         __be16                  cport;
75         __be16                  vport;
76         __be16                  dport;
77         __be32                  caddr;          /* client address */
78         __be32                  vaddr;          /* virtual address */
79         __be32                  daddr;          /* destination address */
80
81         /* Flags and state transition */
82         __be16                  flags;          /* status flags */
83         __be16                  state;          /* state info */
84
85         /* The sequence options start here */
86 };
87
88 struct ip_vs_sync_conn_options {
89         struct ip_vs_seq        in_seq;         /* incoming seq. struct */
90         struct ip_vs_seq        out_seq;        /* outgoing seq. struct */
91 };
92
93 /*
94      Sync Connection format (sync_conn)
95
96        0                   1                   2                   3
97        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
98       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
99       |    Type       |    Protocol   | Ver.  |        Size           |
100       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
101       |                             Flags                             |
102       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
103       |            State              |         cport                 |
104       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
105       |            vport              |         dport                 |
106       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
107       |                             fwmark                            |
108       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
109       |                             timeout  (in sec.)                |
110       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
111       |                              ...                              |
112       |                        IP-Addresses  (v4 or v6)               |
113       |                              ...                              |
114       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
115   Optional Parameters.
116       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
117       | Param. Type    | Param. Length |   Param. data                |
118       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+                               |
119       |                              ...                              |
120       |                               +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
121       |                               | Param Type    | Param. Length |
122       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
123       |                           Param  data                         |
124       |         Last Param data should be padded for 32 bit alignment |
125       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
126 */
127
128 /*
129  *  Type 0, IPv4 sync connection format
130  */
131 struct ip_vs_sync_v4 {
132         __u8                    type;
133         __u8                    protocol;       /* Which protocol (TCP/UDP) */
134         __be16                  ver_size;       /* Version msb 4 bits */
135         /* Flags and state transition */
136         __be32                  flags;          /* status flags */
137         __be16                  state;          /* state info   */
138         /* Protocol, addresses and port numbers */
139         __be16                  cport;
140         __be16                  vport;
141         __be16                  dport;
142         __be32                  fwmark;         /* Firewall mark from skb */
143         __be32                  timeout;        /* cp timeout */
144         __be32                  caddr;          /* client address */
145         __be32                  vaddr;          /* virtual address */
146         __be32                  daddr;          /* destination address */
147         /* The sequence options start here */
148         /* PE data padded to 32bit alignment after seq. options */
149 };
150 /*
151  * Type 2 messages IPv6
152  */
153 struct ip_vs_sync_v6 {
154         __u8                    type;
155         __u8                    protocol;       /* Which protocol (TCP/UDP) */
156         __be16                  ver_size;       /* Version msb 4 bits */
157         /* Flags and state transition */
158         __be32                  flags;          /* status flags */
159         __be16                  state;          /* state info   */
160         /* Protocol, addresses and port numbers */
161         __be16                  cport;
162         __be16                  vport;
163         __be16                  dport;
164         __be32                  fwmark;         /* Firewall mark from skb */
165         __be32                  timeout;        /* cp timeout */
166         struct in6_addr         caddr;          /* client address */
167         struct in6_addr         vaddr;          /* virtual address */
168         struct in6_addr         daddr;          /* destination address */
169         /* The sequence options start here */
170         /* PE data padded to 32bit alignment after seq. options */
171 };
172
173 union ip_vs_sync_conn {
174         struct ip_vs_sync_v4    v4;
175         struct ip_vs_sync_v6    v6;
176 };
177
178 /* Bits in Type field in above */
179 #define STYPE_INET6             0
180 #define STYPE_F_INET6           (1 << STYPE_INET6)
181
182 #define SVER_SHIFT              12              /* Shift to get version */
183 #define SVER_MASK               0x0fff          /* Mask to strip version */
184
185 #define IPVS_OPT_SEQ_DATA       1
186 #define IPVS_OPT_PE_DATA        2
187 #define IPVS_OPT_PE_NAME        3
188 #define IPVS_OPT_PARAM          7
189
190 #define IPVS_OPT_F_SEQ_DATA     (1 << (IPVS_OPT_SEQ_DATA-1))
191 #define IPVS_OPT_F_PE_DATA      (1 << (IPVS_OPT_PE_DATA-1))
192 #define IPVS_OPT_F_PE_NAME      (1 << (IPVS_OPT_PE_NAME-1))
193 #define IPVS_OPT_F_PARAM        (1 << (IPVS_OPT_PARAM-1))
194
195 struct ip_vs_sync_thread_data {
196         struct net *net;
197         struct socket *sock;
198         char *buf;
199         int id;
200 };
201
202 /* Version 0 definition of packet sizes */
203 #define SIMPLE_CONN_SIZE  (sizeof(struct ip_vs_sync_conn_v0))
204 #define FULL_CONN_SIZE  \
205 (sizeof(struct ip_vs_sync_conn_v0) + sizeof(struct ip_vs_sync_conn_options))
206
207
208 /*
209   The master mulitcasts messages (Datagrams) to the backup load balancers
210   in the following format.
211
212  Version 1:
213   Note, first byte should be Zero, so ver 0 receivers will drop the packet.
214
215        0                   1                   2                   3
216        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
217       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
218       |      0        |    SyncID     |            Size               |
219       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
220       |  Count Conns  |    Version    |    Reserved, set to Zero      |
221       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
222       |                                                               |
223       |                    IPVS Sync Connection (1)                   |
224       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
225       |                            .                                  |
226       ~                            .                                  ~
227       |                            .                                  |
228       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
229       |                                                               |
230       |                    IPVS Sync Connection (n)                   |
231       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
232
233  Version 0 Header
234        0                   1                   2                   3
235        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
236       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
237       |  Count Conns  |    SyncID     |            Size               |
238       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
239       |                    IPVS Sync Connection (1)                   |
240 */
241
242 #define SYNC_MESG_HEADER_LEN    4
243 #define MAX_CONNS_PER_SYNCBUFF  255 /* nr_conns in ip_vs_sync_mesg is 8 bit */
244
245 /* Version 0 header */
246 struct ip_vs_sync_mesg_v0 {
247         __u8                    nr_conns;
248         __u8                    syncid;
249         __be16                  size;
250
251         /* ip_vs_sync_conn entries start here */
252 };
253
254 /* Version 1 header */
255 struct ip_vs_sync_mesg {
256         __u8                    reserved;       /* must be zero */
257         __u8                    syncid;
258         __be16                  size;
259         __u8                    nr_conns;
260         __s8                    version;        /* SYNC_PROTO_VER  */
261         __u16                   spare;
262         /* ip_vs_sync_conn entries start here */
263 };
264
265 struct ip_vs_sync_buff {
266         struct list_head        list;
267         unsigned long           firstuse;
268
269         /* pointers for the message data */
270         struct ip_vs_sync_mesg  *mesg;
271         unsigned char           *head;
272         unsigned char           *end;
273 };
274
275 /*
276  * Copy of struct ip_vs_seq
277  * From unaligned network order to aligned host order
278  */
279 static void ntoh_seq(struct ip_vs_seq *no, struct ip_vs_seq *ho)
280 {
281         ho->init_seq       = get_unaligned_be32(&no->init_seq);
282         ho->delta          = get_unaligned_be32(&no->delta);
283         ho->previous_delta = get_unaligned_be32(&no->previous_delta);
284 }
285
286 /*
287  * Copy of struct ip_vs_seq
288  * From Aligned host order to unaligned network order
289  */
290 static void hton_seq(struct ip_vs_seq *ho, struct ip_vs_seq *no)
291 {
292         put_unaligned_be32(ho->init_seq, &no->init_seq);
293         put_unaligned_be32(ho->delta, &no->delta);
294         put_unaligned_be32(ho->previous_delta, &no->previous_delta);
295 }
296
297 static inline struct ip_vs_sync_buff *
298 sb_dequeue(struct netns_ipvs *ipvs, struct ipvs_master_sync_state *ms)
299 {
300         struct ip_vs_sync_buff *sb;
301
302         spin_lock_bh(&ipvs->sync_lock);
303         if (list_empty(&ms->sync_queue)) {
304                 sb = NULL;
305                 __set_current_state(TASK_INTERRUPTIBLE);
306         } else {
307                 sb = list_entry(ms->sync_queue.next, struct ip_vs_sync_buff,
308                                 list);
309                 list_del(&sb->list);
310                 ms->sync_queue_len--;
311                 if (!ms->sync_queue_len)
312                         ms->sync_queue_delay = 0;
313         }
314         spin_unlock_bh(&ipvs->sync_lock);
315
316         return sb;
317 }
318
319 /*
320  * Create a new sync buffer for Version 1 proto.
321  */
322 static inline struct ip_vs_sync_buff *
323 ip_vs_sync_buff_create(struct netns_ipvs *ipvs)
324 {
325         struct ip_vs_sync_buff *sb;
326
327         if (!(sb=kmalloc(sizeof(struct ip_vs_sync_buff), GFP_ATOMIC)))
328                 return NULL;
329
330         sb->mesg = kmalloc(ipvs->send_mesg_maxlen, GFP_ATOMIC);
331         if (!sb->mesg) {
332                 kfree(sb);
333                 return NULL;
334         }
335         sb->mesg->reserved = 0;  /* old nr_conns i.e. must be zero now */
336         sb->mesg->version = SYNC_PROTO_VER;
337         sb->mesg->syncid = ipvs->master_syncid;
338         sb->mesg->size = htons(sizeof(struct ip_vs_sync_mesg));
339         sb->mesg->nr_conns = 0;
340         sb->mesg->spare = 0;
341         sb->head = (unsigned char *)sb->mesg + sizeof(struct ip_vs_sync_mesg);
342         sb->end = (unsigned char *)sb->mesg + ipvs->send_mesg_maxlen;
343
344         sb->firstuse = jiffies;
345         return sb;
346 }
347
348 static inline void ip_vs_sync_buff_release(struct ip_vs_sync_buff *sb)
349 {
350         kfree(sb->mesg);
351         kfree(sb);
352 }
353
354 static inline void sb_queue_tail(struct netns_ipvs *ipvs,
355                                  struct ipvs_master_sync_state *ms)
356 {
357         struct ip_vs_sync_buff *sb = ms->sync_buff;
358
359         spin_lock(&ipvs->sync_lock);
360         if (ipvs->sync_state & IP_VS_STATE_MASTER &&
361             ms->sync_queue_len < sysctl_sync_qlen_max(ipvs)) {
362                 if (!ms->sync_queue_len)
363                         schedule_delayed_work(&ms->master_wakeup_work,
364                                               max(IPVS_SYNC_SEND_DELAY, 1));
365                 ms->sync_queue_len++;
366                 list_add_tail(&sb->list, &ms->sync_queue);
367                 if ((++ms->sync_queue_delay) == IPVS_SYNC_WAKEUP_RATE)
368                         wake_up_process(ms->master_thread);
369         } else
370                 ip_vs_sync_buff_release(sb);
371         spin_unlock(&ipvs->sync_lock);
372 }
373
374 /*
375  *      Get the current sync buffer if it has been created for more
376  *      than the specified time or the specified time is zero.
377  */
378 static inline struct ip_vs_sync_buff *
379 get_curr_sync_buff(struct netns_ipvs *ipvs, struct ipvs_master_sync_state *ms,
380                    unsigned long time)
381 {
382         struct ip_vs_sync_buff *sb;
383
384         spin_lock_bh(&ipvs->sync_buff_lock);
385         sb = ms->sync_buff;
386         if (sb && time_after_eq(jiffies - sb->firstuse, time)) {
387                 ms->sync_buff = NULL;
388                 __set_current_state(TASK_RUNNING);
389         } else
390                 sb = NULL;
391         spin_unlock_bh(&ipvs->sync_buff_lock);
392         return sb;
393 }
394
395 static inline int
396 select_master_thread_id(struct netns_ipvs *ipvs, struct ip_vs_conn *cp)
397 {
398         return ((long) cp >> (1 + ilog2(sizeof(*cp)))) & ipvs->threads_mask;
399 }
400
401 /*
402  * Create a new sync buffer for Version 0 proto.
403  */
404 static inline struct ip_vs_sync_buff *
405 ip_vs_sync_buff_create_v0(struct netns_ipvs *ipvs)
406 {
407         struct ip_vs_sync_buff *sb;
408         struct ip_vs_sync_mesg_v0 *mesg;
409
410         if (!(sb=kmalloc(sizeof(struct ip_vs_sync_buff), GFP_ATOMIC)))
411                 return NULL;
412
413         sb->mesg = kmalloc(ipvs->send_mesg_maxlen, GFP_ATOMIC);
414         if (!sb->mesg) {
415                 kfree(sb);
416                 return NULL;
417         }
418         mesg = (struct ip_vs_sync_mesg_v0 *)sb->mesg;
419         mesg->nr_conns = 0;
420         mesg->syncid = ipvs->master_syncid;
421         mesg->size = htons(sizeof(struct ip_vs_sync_mesg_v0));
422         sb->head = (unsigned char *)mesg + sizeof(struct ip_vs_sync_mesg_v0);
423         sb->end = (unsigned char *)mesg + ipvs->send_mesg_maxlen;
424         sb->firstuse = jiffies;
425         return sb;
426 }
427
428 /* Check if connection is controlled by persistence */
429 static inline bool in_persistence(struct ip_vs_conn *cp)
430 {
431         for (cp = cp->control; cp; cp = cp->control) {
432                 if (cp->flags & IP_VS_CONN_F_TEMPLATE)
433                         return true;
434         }
435         return false;
436 }
437
438 /* Check if conn should be synced.
439  * pkts: conn packets, use sysctl_sync_threshold to avoid packet check
440  * - (1) sync_refresh_period: reduce sync rate. Additionally, retry
441  *      sync_retries times with period of sync_refresh_period/8
442  * - (2) if both sync_refresh_period and sync_period are 0 send sync only
443  *      for state changes or only once when pkts matches sync_threshold
444  * - (3) templates: rate can be reduced only with sync_refresh_period or
445  *      with (2)
446  */
447 static int ip_vs_sync_conn_needed(struct netns_ipvs *ipvs,
448                                   struct ip_vs_conn *cp, int pkts)
449 {
450         unsigned long orig = ACCESS_ONCE(cp->sync_endtime);
451         unsigned long now = jiffies;
452         unsigned long n = (now + cp->timeout) & ~3UL;
453         unsigned int sync_refresh_period;
454         int sync_period;
455         int force;
456
457         /* Check if we sync in current state */
458         if (unlikely(cp->flags & IP_VS_CONN_F_TEMPLATE))
459                 force = 0;
460         else if (unlikely(sysctl_sync_persist_mode(ipvs) && in_persistence(cp)))
461                 return 0;
462         else if (likely(cp->protocol == IPPROTO_TCP)) {
463                 if (!((1 << cp->state) &
464                       ((1 << IP_VS_TCP_S_ESTABLISHED) |
465                        (1 << IP_VS_TCP_S_FIN_WAIT) |
466                        (1 << IP_VS_TCP_S_CLOSE) |
467                        (1 << IP_VS_TCP_S_CLOSE_WAIT) |
468                        (1 << IP_VS_TCP_S_TIME_WAIT))))
469                         return 0;
470                 force = cp->state != cp->old_state;
471                 if (force && cp->state != IP_VS_TCP_S_ESTABLISHED)
472                         goto set;
473         } else if (unlikely(cp->protocol == IPPROTO_SCTP)) {
474                 if (!((1 << cp->state) &
475                       ((1 << IP_VS_SCTP_S_ESTABLISHED) |
476                        (1 << IP_VS_SCTP_S_SHUTDOWN_SENT) |
477                        (1 << IP_VS_SCTP_S_SHUTDOWN_RECEIVED) |
478                        (1 << IP_VS_SCTP_S_SHUTDOWN_ACK_SENT) |
479                        (1 << IP_VS_SCTP_S_CLOSED))))
480                         return 0;
481                 force = cp->state != cp->old_state;
482                 if (force && cp->state != IP_VS_SCTP_S_ESTABLISHED)
483                         goto set;
484         } else {
485                 /* UDP or another protocol with single state */
486                 force = 0;
487         }
488
489         sync_refresh_period = sysctl_sync_refresh_period(ipvs);
490         if (sync_refresh_period > 0) {
491                 long diff = n - orig;
492                 long min_diff = max(cp->timeout >> 1, 10UL * HZ);
493
494                 /* Avoid sync if difference is below sync_refresh_period
495                  * and below the half timeout.
496                  */
497                 if (abs(diff) < min_t(long, sync_refresh_period, min_diff)) {
498                         int retries = orig & 3;
499
500                         if (retries >= sysctl_sync_retries(ipvs))
501                                 return 0;
502                         if (time_before(now, orig - cp->timeout +
503                                         (sync_refresh_period >> 3)))
504                                 return 0;
505                         n |= retries + 1;
506                 }
507         }
508         sync_period = sysctl_sync_period(ipvs);
509         if (sync_period > 0) {
510                 if (!(cp->flags & IP_VS_CONN_F_TEMPLATE) &&
511                     pkts % sync_period != sysctl_sync_threshold(ipvs))
512                         return 0;
513         } else if (sync_refresh_period <= 0 &&
514                    pkts != sysctl_sync_threshold(ipvs))
515                 return 0;
516
517 set:
518         cp->old_state = cp->state;
519         n = cmpxchg(&cp->sync_endtime, orig, n);
520         return n == orig || force;
521 }
522
523 /*
524  *      Version 0 , could be switched in by sys_ctl.
525  *      Add an ip_vs_conn information into the current sync_buff.
526  */
527 static void ip_vs_sync_conn_v0(struct net *net, struct ip_vs_conn *cp,
528                                int pkts)
529 {
530         struct netns_ipvs *ipvs = net_ipvs(net);
531         struct ip_vs_sync_mesg_v0 *m;
532         struct ip_vs_sync_conn_v0 *s;
533         struct ip_vs_sync_buff *buff;
534         struct ipvs_master_sync_state *ms;
535         int id;
536         int len;
537
538         if (unlikely(cp->af != AF_INET))
539                 return;
540         /* Do not sync ONE PACKET */
541         if (cp->flags & IP_VS_CONN_F_ONE_PACKET)
542                 return;
543
544         if (!ip_vs_sync_conn_needed(ipvs, cp, pkts))
545                 return;
546
547         spin_lock_bh(&ipvs->sync_buff_lock);
548         if (!(ipvs->sync_state & IP_VS_STATE_MASTER)) {
549                 spin_unlock_bh(&ipvs->sync_buff_lock);
550                 return;
551         }
552
553         id = select_master_thread_id(ipvs, cp);
554         ms = &ipvs->ms[id];
555         buff = ms->sync_buff;
556         if (buff) {
557                 m = (struct ip_vs_sync_mesg_v0 *) buff->mesg;
558                 /* Send buffer if it is for v1 */
559                 if (!m->nr_conns) {
560                         sb_queue_tail(ipvs, ms);
561                         ms->sync_buff = NULL;
562                         buff = NULL;
563                 }
564         }
565         if (!buff) {
566                 buff = ip_vs_sync_buff_create_v0(ipvs);
567                 if (!buff) {
568                         spin_unlock_bh(&ipvs->sync_buff_lock);
569                         pr_err("ip_vs_sync_buff_create failed.\n");
570                         return;
571                 }
572                 ms->sync_buff = buff;
573         }
574
575         len = (cp->flags & IP_VS_CONN_F_SEQ_MASK) ? FULL_CONN_SIZE :
576                 SIMPLE_CONN_SIZE;
577         m = (struct ip_vs_sync_mesg_v0 *) buff->mesg;
578         s = (struct ip_vs_sync_conn_v0 *) buff->head;
579
580         /* copy members */
581         s->reserved = 0;
582         s->protocol = cp->protocol;
583         s->cport = cp->cport;
584         s->vport = cp->vport;
585         s->dport = cp->dport;
586         s->caddr = cp->caddr.ip;
587         s->vaddr = cp->vaddr.ip;
588         s->daddr = cp->daddr.ip;
589         s->flags = htons(cp->flags & ~IP_VS_CONN_F_HASHED);
590         s->state = htons(cp->state);
591         if (cp->flags & IP_VS_CONN_F_SEQ_MASK) {
592                 struct ip_vs_sync_conn_options *opt =
593                         (struct ip_vs_sync_conn_options *)&s[1];
594                 memcpy(opt, &cp->in_seq, sizeof(*opt));
595         }
596
597         m->nr_conns++;
598         m->size = htons(ntohs(m->size) + len);
599         buff->head += len;
600
601         /* check if there is a space for next one */
602         if (buff->head + FULL_CONN_SIZE > buff->end) {
603                 sb_queue_tail(ipvs, ms);
604                 ms->sync_buff = NULL;
605         }
606         spin_unlock_bh(&ipvs->sync_buff_lock);
607
608         /* synchronize its controller if it has */
609         cp = cp->control;
610         if (cp) {
611                 if (cp->flags & IP_VS_CONN_F_TEMPLATE)
612                         pkts = atomic_add_return(1, &cp->in_pkts);
613                 else
614                         pkts = sysctl_sync_threshold(ipvs);
615                 ip_vs_sync_conn(net, cp->control, pkts);
616         }
617 }
618
619 /*
620  *      Add an ip_vs_conn information into the current sync_buff.
621  *      Called by ip_vs_in.
622  *      Sending Version 1 messages
623  */
624 void ip_vs_sync_conn(struct net *net, struct ip_vs_conn *cp, int pkts)
625 {
626         struct netns_ipvs *ipvs = net_ipvs(net);
627         struct ip_vs_sync_mesg *m;
628         union ip_vs_sync_conn *s;
629         struct ip_vs_sync_buff *buff;
630         struct ipvs_master_sync_state *ms;
631         int id;
632         __u8 *p;
633         unsigned int len, pe_name_len, pad;
634
635         /* Handle old version of the protocol */
636         if (sysctl_sync_ver(ipvs) == 0) {
637                 ip_vs_sync_conn_v0(net, cp, pkts);
638                 return;
639         }
640         /* Do not sync ONE PACKET */
641         if (cp->flags & IP_VS_CONN_F_ONE_PACKET)
642                 goto control;
643 sloop:
644         if (!ip_vs_sync_conn_needed(ipvs, cp, pkts))
645                 goto control;
646
647         /* Sanity checks */
648         pe_name_len = 0;
649         if (cp->pe_data_len) {
650                 if (!cp->pe_data || !cp->dest) {
651                         IP_VS_ERR_RL("SYNC, connection pe_data invalid\n");
652                         return;
653                 }
654                 pe_name_len = strnlen(cp->pe->name, IP_VS_PENAME_MAXLEN);
655         }
656
657         spin_lock_bh(&ipvs->sync_buff_lock);
658         if (!(ipvs->sync_state & IP_VS_STATE_MASTER)) {
659                 spin_unlock_bh(&ipvs->sync_buff_lock);
660                 return;
661         }
662
663         id = select_master_thread_id(ipvs, cp);
664         ms = &ipvs->ms[id];
665
666 #ifdef CONFIG_IP_VS_IPV6
667         if (cp->af == AF_INET6)
668                 len = sizeof(struct ip_vs_sync_v6);
669         else
670 #endif
671                 len = sizeof(struct ip_vs_sync_v4);
672
673         if (cp->flags & IP_VS_CONN_F_SEQ_MASK)
674                 len += sizeof(struct ip_vs_sync_conn_options) + 2;
675
676         if (cp->pe_data_len)
677                 len += cp->pe_data_len + 2;     /* + Param hdr field */
678         if (pe_name_len)
679                 len += pe_name_len + 2;
680
681         /* check if there is a space for this one  */
682         pad = 0;
683         buff = ms->sync_buff;
684         if (buff) {
685                 m = buff->mesg;
686                 pad = (4 - (size_t) buff->head) & 3;
687                 /* Send buffer if it is for v0 */
688                 if (buff->head + len + pad > buff->end || m->reserved) {
689                         sb_queue_tail(ipvs, ms);
690                         ms->sync_buff = NULL;
691                         buff = NULL;
692                         pad = 0;
693                 }
694         }
695
696         if (!buff) {
697                 buff = ip_vs_sync_buff_create(ipvs);
698                 if (!buff) {
699                         spin_unlock_bh(&ipvs->sync_buff_lock);
700                         pr_err("ip_vs_sync_buff_create failed.\n");
701                         return;
702                 }
703                 ms->sync_buff = buff;
704                 m = buff->mesg;
705         }
706
707         p = buff->head;
708         buff->head += pad + len;
709         m->size = htons(ntohs(m->size) + pad + len);
710         /* Add ev. padding from prev. sync_conn */
711         while (pad--)
712                 *(p++) = 0;
713
714         s = (union ip_vs_sync_conn *)p;
715
716         /* Set message type  & copy members */
717         s->v4.type = (cp->af == AF_INET6 ? STYPE_F_INET6 : 0);
718         s->v4.ver_size = htons(len & SVER_MASK);        /* Version 0 */
719         s->v4.flags = htonl(cp->flags & ~IP_VS_CONN_F_HASHED);
720         s->v4.state = htons(cp->state);
721         s->v4.protocol = cp->protocol;
722         s->v4.cport = cp->cport;
723         s->v4.vport = cp->vport;
724         s->v4.dport = cp->dport;
725         s->v4.fwmark = htonl(cp->fwmark);
726         s->v4.timeout = htonl(cp->timeout / HZ);
727         m->nr_conns++;
728
729 #ifdef CONFIG_IP_VS_IPV6
730         if (cp->af == AF_INET6) {
731                 p += sizeof(struct ip_vs_sync_v6);
732                 s->v6.caddr = cp->caddr.in6;
733                 s->v6.vaddr = cp->vaddr.in6;
734                 s->v6.daddr = cp->daddr.in6;
735         } else
736 #endif
737         {
738                 p += sizeof(struct ip_vs_sync_v4);      /* options ptr */
739                 s->v4.caddr = cp->caddr.ip;
740                 s->v4.vaddr = cp->vaddr.ip;
741                 s->v4.daddr = cp->daddr.ip;
742         }
743         if (cp->flags & IP_VS_CONN_F_SEQ_MASK) {
744                 *(p++) = IPVS_OPT_SEQ_DATA;
745                 *(p++) = sizeof(struct ip_vs_sync_conn_options);
746                 hton_seq((struct ip_vs_seq *)p, &cp->in_seq);
747                 p += sizeof(struct ip_vs_seq);
748                 hton_seq((struct ip_vs_seq *)p, &cp->out_seq);
749                 p += sizeof(struct ip_vs_seq);
750         }
751         /* Handle pe data */
752         if (cp->pe_data_len && cp->pe_data) {
753                 *(p++) = IPVS_OPT_PE_DATA;
754                 *(p++) = cp->pe_data_len;
755                 memcpy(p, cp->pe_data, cp->pe_data_len);
756                 p += cp->pe_data_len;
757                 if (pe_name_len) {
758                         /* Add PE_NAME */
759                         *(p++) = IPVS_OPT_PE_NAME;
760                         *(p++) = pe_name_len;
761                         memcpy(p, cp->pe->name, pe_name_len);
762                         p += pe_name_len;
763                 }
764         }
765
766         spin_unlock_bh(&ipvs->sync_buff_lock);
767
768 control:
769         /* synchronize its controller if it has */
770         cp = cp->control;
771         if (!cp)
772                 return;
773         if (cp->flags & IP_VS_CONN_F_TEMPLATE)
774                 pkts = atomic_add_return(1, &cp->in_pkts);
775         else
776                 pkts = sysctl_sync_threshold(ipvs);
777         goto sloop;
778 }
779
780 /*
781  *  fill_param used by version 1
782  */
783 static inline int
784 ip_vs_conn_fill_param_sync(struct net *net, int af, union ip_vs_sync_conn *sc,
785                            struct ip_vs_conn_param *p,
786                            __u8 *pe_data, unsigned int pe_data_len,
787                            __u8 *pe_name, unsigned int pe_name_len)
788 {
789 #ifdef CONFIG_IP_VS_IPV6
790         if (af == AF_INET6)
791                 ip_vs_conn_fill_param(net, af, sc->v6.protocol,
792                                       (const union nf_inet_addr *)&sc->v6.caddr,
793                                       sc->v6.cport,
794                                       (const union nf_inet_addr *)&sc->v6.vaddr,
795                                       sc->v6.vport, p);
796         else
797 #endif
798                 ip_vs_conn_fill_param(net, af, sc->v4.protocol,
799                                       (const union nf_inet_addr *)&sc->v4.caddr,
800                                       sc->v4.cport,
801                                       (const union nf_inet_addr *)&sc->v4.vaddr,
802                                       sc->v4.vport, p);
803         /* Handle pe data */
804         if (pe_data_len) {
805                 if (pe_name_len) {
806                         char buff[IP_VS_PENAME_MAXLEN+1];
807
808                         memcpy(buff, pe_name, pe_name_len);
809                         buff[pe_name_len]=0;
810                         p->pe = __ip_vs_pe_getbyname(buff);
811                         if (!p->pe) {
812                                 IP_VS_DBG(3, "BACKUP, no %s engine found/loaded\n",
813                                              buff);
814                                 return 1;
815                         }
816                 } else {
817                         IP_VS_ERR_RL("BACKUP, Invalid PE parameters\n");
818                         return 1;
819                 }
820
821                 p->pe_data = kmemdup(pe_data, pe_data_len, GFP_ATOMIC);
822                 if (!p->pe_data) {
823                         module_put(p->pe->module);
824                         return -ENOMEM;
825                 }
826                 p->pe_data_len = pe_data_len;
827         }
828         return 0;
829 }
830
831 /*
832  *  Connection Add / Update.
833  *  Common for version 0 and 1 reception of backup sync_conns.
834  *  Param: ...
835  *         timeout is in sec.
836  */
837 static void ip_vs_proc_conn(struct net *net, struct ip_vs_conn_param *param,
838                             unsigned int flags, unsigned int state,
839                             unsigned int protocol, unsigned int type,
840                             const union nf_inet_addr *daddr, __be16 dport,
841                             unsigned long timeout, __u32 fwmark,
842                             struct ip_vs_sync_conn_options *opt)
843 {
844         struct ip_vs_dest *dest;
845         struct ip_vs_conn *cp;
846         struct netns_ipvs *ipvs = net_ipvs(net);
847
848         if (!(flags & IP_VS_CONN_F_TEMPLATE))
849                 cp = ip_vs_conn_in_get(param);
850         else
851                 cp = ip_vs_ct_in_get(param);
852
853         if (cp) {
854                 /* Free pe_data */
855                 kfree(param->pe_data);
856
857                 dest = cp->dest;
858                 spin_lock_bh(&cp->lock);
859                 if ((cp->flags ^ flags) & IP_VS_CONN_F_INACTIVE &&
860                     !(flags & IP_VS_CONN_F_TEMPLATE) && dest) {
861                         if (flags & IP_VS_CONN_F_INACTIVE) {
862                                 atomic_dec(&dest->activeconns);
863                                 atomic_inc(&dest->inactconns);
864                         } else {
865                                 atomic_inc(&dest->activeconns);
866                                 atomic_dec(&dest->inactconns);
867                         }
868                 }
869                 flags &= IP_VS_CONN_F_BACKUP_UPD_MASK;
870                 flags |= cp->flags & ~IP_VS_CONN_F_BACKUP_UPD_MASK;
871                 cp->flags = flags;
872                 spin_unlock_bh(&cp->lock);
873                 if (!dest)
874                         ip_vs_try_bind_dest(cp);
875         } else {
876                 /*
877                  * Find the appropriate destination for the connection.
878                  * If it is not found the connection will remain unbound
879                  * but still handled.
880                  */
881                 rcu_read_lock();
882                 /* This function is only invoked by the synchronization
883                  * code. We do not currently support heterogeneous pools
884                  * with synchronization, so we can make the assumption that
885                  * the svc_af is the same as the dest_af
886                  */
887                 dest = ip_vs_find_dest(net, type, type, daddr, dport,
888                                        param->vaddr, param->vport, protocol,
889                                        fwmark, flags);
890
891                 cp = ip_vs_conn_new(param, type, daddr, dport, flags, dest,
892                                     fwmark);
893                 rcu_read_unlock();
894                 if (!cp) {
895                         kfree(param->pe_data);
896                         IP_VS_DBG(2, "BACKUP, add new conn. failed\n");
897                         return;
898                 }
899                 if (!(flags & IP_VS_CONN_F_TEMPLATE))
900                         kfree(param->pe_data);
901         }
902
903         if (opt)
904                 memcpy(&cp->in_seq, opt, sizeof(*opt));
905         atomic_set(&cp->in_pkts, sysctl_sync_threshold(ipvs));
906         cp->state = state;
907         cp->old_state = cp->state;
908         /*
909          * For Ver 0 messages style
910          *  - Not possible to recover the right timeout for templates
911          *  - can not find the right fwmark
912          *    virtual service. If needed, we can do it for
913          *    non-fwmark persistent services.
914          * Ver 1 messages style.
915          *  - No problem.
916          */
917         if (timeout) {
918                 if (timeout > MAX_SCHEDULE_TIMEOUT / HZ)
919                         timeout = MAX_SCHEDULE_TIMEOUT / HZ;
920                 cp->timeout = timeout*HZ;
921         } else {
922                 struct ip_vs_proto_data *pd;
923
924                 pd = ip_vs_proto_data_get(net, protocol);
925                 if (!(flags & IP_VS_CONN_F_TEMPLATE) && pd && pd->timeout_table)
926                         cp->timeout = pd->timeout_table[state];
927                 else
928                         cp->timeout = (3*60*HZ);
929         }
930         ip_vs_conn_put(cp);
931 }
932
933 /*
934  *  Process received multicast message for Version 0
935  */
936 static void ip_vs_process_message_v0(struct net *net, const char *buffer,
937                                      const size_t buflen)
938 {
939         struct ip_vs_sync_mesg_v0 *m = (struct ip_vs_sync_mesg_v0 *)buffer;
940         struct ip_vs_sync_conn_v0 *s;
941         struct ip_vs_sync_conn_options *opt;
942         struct ip_vs_protocol *pp;
943         struct ip_vs_conn_param param;
944         char *p;
945         int i;
946
947         p = (char *)buffer + sizeof(struct ip_vs_sync_mesg_v0);
948         for (i=0; i<m->nr_conns; i++) {
949                 unsigned int flags, state;
950
951                 if (p + SIMPLE_CONN_SIZE > buffer+buflen) {
952                         IP_VS_ERR_RL("BACKUP v0, bogus conn\n");
953                         return;
954                 }
955                 s = (struct ip_vs_sync_conn_v0 *) p;
956                 flags = ntohs(s->flags) | IP_VS_CONN_F_SYNC;
957                 flags &= ~IP_VS_CONN_F_HASHED;
958                 if (flags & IP_VS_CONN_F_SEQ_MASK) {
959                         opt = (struct ip_vs_sync_conn_options *)&s[1];
960                         p += FULL_CONN_SIZE;
961                         if (p > buffer+buflen) {
962                                 IP_VS_ERR_RL("BACKUP v0, Dropping buffer bogus conn options\n");
963                                 return;
964                         }
965                 } else {
966                         opt = NULL;
967                         p += SIMPLE_CONN_SIZE;
968                 }
969
970                 state = ntohs(s->state);
971                 if (!(flags & IP_VS_CONN_F_TEMPLATE)) {
972                         pp = ip_vs_proto_get(s->protocol);
973                         if (!pp) {
974                                 IP_VS_DBG(2, "BACKUP v0, Unsupported protocol %u\n",
975                                         s->protocol);
976                                 continue;
977                         }
978                         if (state >= pp->num_states) {
979                                 IP_VS_DBG(2, "BACKUP v0, Invalid %s state %u\n",
980                                         pp->name, state);
981                                 continue;
982                         }
983                 } else {
984                         /* protocol in templates is not used for state/timeout */
985                         if (state > 0) {
986                                 IP_VS_DBG(2, "BACKUP v0, Invalid template state %u\n",
987                                         state);
988                                 state = 0;
989                         }
990                 }
991
992                 ip_vs_conn_fill_param(net, AF_INET, s->protocol,
993                                       (const union nf_inet_addr *)&s->caddr,
994                                       s->cport,
995                                       (const union nf_inet_addr *)&s->vaddr,
996                                       s->vport, &param);
997
998                 /* Send timeout as Zero */
999                 ip_vs_proc_conn(net, &param, flags, state, s->protocol, AF_INET,
1000                                 (union nf_inet_addr *)&s->daddr, s->dport,
1001                                 0, 0, opt);
1002         }
1003 }
1004
1005 /*
1006  * Handle options
1007  */
1008 static inline int ip_vs_proc_seqopt(__u8 *p, unsigned int plen,
1009                                     __u32 *opt_flags,
1010                                     struct ip_vs_sync_conn_options *opt)
1011 {
1012         struct ip_vs_sync_conn_options *topt;
1013
1014         topt = (struct ip_vs_sync_conn_options *)p;
1015
1016         if (plen != sizeof(struct ip_vs_sync_conn_options)) {
1017                 IP_VS_DBG(2, "BACKUP, bogus conn options length\n");
1018                 return -EINVAL;
1019         }
1020         if (*opt_flags & IPVS_OPT_F_SEQ_DATA) {
1021                 IP_VS_DBG(2, "BACKUP, conn options found twice\n");
1022                 return -EINVAL;
1023         }
1024         ntoh_seq(&topt->in_seq, &opt->in_seq);
1025         ntoh_seq(&topt->out_seq, &opt->out_seq);
1026         *opt_flags |= IPVS_OPT_F_SEQ_DATA;
1027         return 0;
1028 }
1029
1030 static int ip_vs_proc_str(__u8 *p, unsigned int plen, unsigned int *data_len,
1031                           __u8 **data, unsigned int maxlen,
1032                           __u32 *opt_flags, __u32 flag)
1033 {
1034         if (plen > maxlen) {
1035                 IP_VS_DBG(2, "BACKUP, bogus par.data len > %d\n", maxlen);
1036                 return -EINVAL;
1037         }
1038         if (*opt_flags & flag) {
1039                 IP_VS_DBG(2, "BACKUP, Par.data found twice 0x%x\n", flag);
1040                 return -EINVAL;
1041         }
1042         *data_len = plen;
1043         *data = p;
1044         *opt_flags |= flag;
1045         return 0;
1046 }
1047 /*
1048  *   Process a Version 1 sync. connection
1049  */
1050 static inline int ip_vs_proc_sync_conn(struct net *net, __u8 *p, __u8 *msg_end)
1051 {
1052         struct ip_vs_sync_conn_options opt;
1053         union  ip_vs_sync_conn *s;
1054         struct ip_vs_protocol *pp;
1055         struct ip_vs_conn_param param;
1056         __u32 flags;
1057         unsigned int af, state, pe_data_len=0, pe_name_len=0;
1058         __u8 *pe_data=NULL, *pe_name=NULL;
1059         __u32 opt_flags=0;
1060         int retc=0;
1061
1062         s = (union ip_vs_sync_conn *) p;
1063
1064         if (s->v6.type & STYPE_F_INET6) {
1065 #ifdef CONFIG_IP_VS_IPV6
1066                 af = AF_INET6;
1067                 p += sizeof(struct ip_vs_sync_v6);
1068 #else
1069                 IP_VS_DBG(3,"BACKUP, IPv6 msg received, and IPVS is not compiled for IPv6\n");
1070                 retc = 10;
1071                 goto out;
1072 #endif
1073         } else if (!s->v4.type) {
1074                 af = AF_INET;
1075                 p += sizeof(struct ip_vs_sync_v4);
1076         } else {
1077                 return -10;
1078         }
1079         if (p > msg_end)
1080                 return -20;
1081
1082         /* Process optional params check Type & Len. */
1083         while (p < msg_end) {
1084                 int ptype;
1085                 int plen;
1086
1087                 if (p+2 > msg_end)
1088                         return -30;
1089                 ptype = *(p++);
1090                 plen  = *(p++);
1091
1092                 if (!plen || ((p + plen) > msg_end))
1093                         return -40;
1094                 /* Handle seq option  p = param data */
1095                 switch (ptype & ~IPVS_OPT_F_PARAM) {
1096                 case IPVS_OPT_SEQ_DATA:
1097                         if (ip_vs_proc_seqopt(p, plen, &opt_flags, &opt))
1098                                 return -50;
1099                         break;
1100
1101                 case IPVS_OPT_PE_DATA:
1102                         if (ip_vs_proc_str(p, plen, &pe_data_len, &pe_data,
1103                                            IP_VS_PEDATA_MAXLEN, &opt_flags,
1104                                            IPVS_OPT_F_PE_DATA))
1105                                 return -60;
1106                         break;
1107
1108                 case IPVS_OPT_PE_NAME:
1109                         if (ip_vs_proc_str(p, plen,&pe_name_len, &pe_name,
1110                                            IP_VS_PENAME_MAXLEN, &opt_flags,
1111                                            IPVS_OPT_F_PE_NAME))
1112                                 return -70;
1113                         break;
1114
1115                 default:
1116                         /* Param data mandatory ? */
1117                         if (!(ptype & IPVS_OPT_F_PARAM)) {
1118                                 IP_VS_DBG(3, "BACKUP, Unknown mandatory param %d found\n",
1119                                           ptype & ~IPVS_OPT_F_PARAM);
1120                                 retc = 20;
1121                                 goto out;
1122                         }
1123                 }
1124                 p += plen;  /* Next option */
1125         }
1126
1127         /* Get flags and Mask off unsupported */
1128         flags  = ntohl(s->v4.flags) & IP_VS_CONN_F_BACKUP_MASK;
1129         flags |= IP_VS_CONN_F_SYNC;
1130         state = ntohs(s->v4.state);
1131
1132         if (!(flags & IP_VS_CONN_F_TEMPLATE)) {
1133                 pp = ip_vs_proto_get(s->v4.protocol);
1134                 if (!pp) {
1135                         IP_VS_DBG(3,"BACKUP, Unsupported protocol %u\n",
1136                                 s->v4.protocol);
1137                         retc = 30;
1138                         goto out;
1139                 }
1140                 if (state >= pp->num_states) {
1141                         IP_VS_DBG(3, "BACKUP, Invalid %s state %u\n",
1142                                 pp->name, state);
1143                         retc = 40;
1144                         goto out;
1145                 }
1146         } else {
1147                 /* protocol in templates is not used for state/timeout */
1148                 if (state > 0) {
1149                         IP_VS_DBG(3, "BACKUP, Invalid template state %u\n",
1150                                 state);
1151                         state = 0;
1152                 }
1153         }
1154         if (ip_vs_conn_fill_param_sync(net, af, s, &param, pe_data,
1155                                        pe_data_len, pe_name, pe_name_len)) {
1156                 retc = 50;
1157                 goto out;
1158         }
1159         /* If only IPv4, just silent skip IPv6 */
1160         if (af == AF_INET)
1161                 ip_vs_proc_conn(net, &param, flags, state, s->v4.protocol, af,
1162                                 (union nf_inet_addr *)&s->v4.daddr, s->v4.dport,
1163                                 ntohl(s->v4.timeout), ntohl(s->v4.fwmark),
1164                                 (opt_flags & IPVS_OPT_F_SEQ_DATA ? &opt : NULL)
1165                                 );
1166 #ifdef CONFIG_IP_VS_IPV6
1167         else
1168                 ip_vs_proc_conn(net, &param, flags, state, s->v6.protocol, af,
1169                                 (union nf_inet_addr *)&s->v6.daddr, s->v6.dport,
1170                                 ntohl(s->v6.timeout), ntohl(s->v6.fwmark),
1171                                 (opt_flags & IPVS_OPT_F_SEQ_DATA ? &opt : NULL)
1172                                 );
1173 #endif
1174         ip_vs_pe_put(param.pe);
1175         return 0;
1176         /* Error exit */
1177 out:
1178         IP_VS_DBG(2, "BACKUP, Single msg dropped err:%d\n", retc);
1179         return retc;
1180
1181 }
1182 /*
1183  *      Process received multicast message and create the corresponding
1184  *      ip_vs_conn entries.
1185  *      Handles Version 0 & 1
1186  */
1187 static void ip_vs_process_message(struct net *net, __u8 *buffer,
1188                                   const size_t buflen)
1189 {
1190         struct netns_ipvs *ipvs = net_ipvs(net);
1191         struct ip_vs_sync_mesg *m2 = (struct ip_vs_sync_mesg *)buffer;
1192         __u8 *p, *msg_end;
1193         int i, nr_conns;
1194
1195         if (buflen < sizeof(struct ip_vs_sync_mesg_v0)) {
1196                 IP_VS_DBG(2, "BACKUP, message header too short\n");
1197                 return;
1198         }
1199
1200         if (buflen != ntohs(m2->size)) {
1201                 IP_VS_DBG(2, "BACKUP, bogus message size\n");
1202                 return;
1203         }
1204         /* SyncID sanity check */
1205         if (ipvs->backup_syncid != 0 && m2->syncid != ipvs->backup_syncid) {
1206                 IP_VS_DBG(7, "BACKUP, Ignoring syncid = %d\n", m2->syncid);
1207                 return;
1208         }
1209         /* Handle version 1  message */
1210         if ((m2->version == SYNC_PROTO_VER) && (m2->reserved == 0)
1211             && (m2->spare == 0)) {
1212
1213                 msg_end = buffer + sizeof(struct ip_vs_sync_mesg);
1214                 nr_conns = m2->nr_conns;
1215
1216                 for (i=0; i<nr_conns; i++) {
1217                         union ip_vs_sync_conn *s;
1218                         unsigned int size;
1219                         int retc;
1220
1221                         p = msg_end;
1222                         if (p + sizeof(s->v4) > buffer+buflen) {
1223                                 IP_VS_ERR_RL("BACKUP, Dropping buffer, to small\n");
1224                                 return;
1225                         }
1226                         s = (union ip_vs_sync_conn *)p;
1227                         size = ntohs(s->v4.ver_size) & SVER_MASK;
1228                         msg_end = p + size;
1229                         /* Basic sanity checks */
1230                         if (msg_end  > buffer+buflen) {
1231                                 IP_VS_ERR_RL("BACKUP, Dropping buffer, msg > buffer\n");
1232                                 return;
1233                         }
1234                         if (ntohs(s->v4.ver_size) >> SVER_SHIFT) {
1235                                 IP_VS_ERR_RL("BACKUP, Dropping buffer, Unknown version %d\n",
1236                                               ntohs(s->v4.ver_size) >> SVER_SHIFT);
1237                                 return;
1238                         }
1239                         /* Process a single sync_conn */
1240                         retc = ip_vs_proc_sync_conn(net, p, msg_end);
1241                         if (retc < 0) {
1242                                 IP_VS_ERR_RL("BACKUP, Dropping buffer, Err: %d in decoding\n",
1243                                              retc);
1244                                 return;
1245                         }
1246                         /* Make sure we have 32 bit alignment */
1247                         msg_end = p + ((size + 3) & ~3);
1248                 }
1249         } else {
1250                 /* Old type of message */
1251                 ip_vs_process_message_v0(net, buffer, buflen);
1252                 return;
1253         }
1254 }
1255
1256
1257 /*
1258  *      Setup sndbuf (mode=1) or rcvbuf (mode=0)
1259  */
1260 static void set_sock_size(struct sock *sk, int mode, int val)
1261 {
1262         /* setsockopt(sock, SOL_SOCKET, SO_SNDBUF, &val, sizeof(val)); */
1263         /* setsockopt(sock, SOL_SOCKET, SO_RCVBUF, &val, sizeof(val)); */
1264         lock_sock(sk);
1265         if (mode) {
1266                 val = clamp_t(int, val, (SOCK_MIN_SNDBUF + 1) / 2,
1267                               sysctl_wmem_max);
1268                 sk->sk_sndbuf = val * 2;
1269                 sk->sk_userlocks |= SOCK_SNDBUF_LOCK;
1270         } else {
1271                 val = clamp_t(int, val, (SOCK_MIN_RCVBUF + 1) / 2,
1272                               sysctl_rmem_max);
1273                 sk->sk_rcvbuf = val * 2;
1274                 sk->sk_userlocks |= SOCK_RCVBUF_LOCK;
1275         }
1276         release_sock(sk);
1277 }
1278
1279 /*
1280  *      Setup loopback of outgoing multicasts on a sending socket
1281  */
1282 static void set_mcast_loop(struct sock *sk, u_char loop)
1283 {
1284         struct inet_sock *inet = inet_sk(sk);
1285
1286         /* setsockopt(sock, SOL_IP, IP_MULTICAST_LOOP, &loop, sizeof(loop)); */
1287         lock_sock(sk);
1288         inet->mc_loop = loop ? 1 : 0;
1289         release_sock(sk);
1290 }
1291
1292 /*
1293  *      Specify TTL for outgoing multicasts on a sending socket
1294  */
1295 static void set_mcast_ttl(struct sock *sk, u_char ttl)
1296 {
1297         struct inet_sock *inet = inet_sk(sk);
1298
1299         /* setsockopt(sock, SOL_IP, IP_MULTICAST_TTL, &ttl, sizeof(ttl)); */
1300         lock_sock(sk);
1301         inet->mc_ttl = ttl;
1302         release_sock(sk);
1303 }
1304
1305 /*
1306  *      Specifiy default interface for outgoing multicasts
1307  */
1308 static int set_mcast_if(struct sock *sk, char *ifname)
1309 {
1310         struct net_device *dev;
1311         struct inet_sock *inet = inet_sk(sk);
1312         struct net *net = sock_net(sk);
1313
1314         dev = __dev_get_by_name(net, ifname);
1315         if (!dev)
1316                 return -ENODEV;
1317
1318         if (sk->sk_bound_dev_if && dev->ifindex != sk->sk_bound_dev_if)
1319                 return -EINVAL;
1320
1321         lock_sock(sk);
1322         inet->mc_index = dev->ifindex;
1323         /*  inet->mc_addr  = 0; */
1324         release_sock(sk);
1325
1326         return 0;
1327 }
1328
1329
1330 /*
1331  *      Set the maximum length of sync message according to the
1332  *      specified interface's MTU.
1333  */
1334 static int set_sync_mesg_maxlen(struct net *net, int sync_state)
1335 {
1336         struct netns_ipvs *ipvs = net_ipvs(net);
1337         struct net_device *dev;
1338         int num;
1339
1340         if (sync_state == IP_VS_STATE_MASTER) {
1341                 dev = __dev_get_by_name(net, ipvs->master_mcast_ifn);
1342                 if (!dev)
1343                         return -ENODEV;
1344
1345                 num = (dev->mtu - sizeof(struct iphdr) -
1346                        sizeof(struct udphdr) -
1347                        SYNC_MESG_HEADER_LEN - 20) / SIMPLE_CONN_SIZE;
1348                 ipvs->send_mesg_maxlen = SYNC_MESG_HEADER_LEN +
1349                         SIMPLE_CONN_SIZE * min(num, MAX_CONNS_PER_SYNCBUFF);
1350                 IP_VS_DBG(7, "setting the maximum length of sync sending "
1351                           "message %d.\n", ipvs->send_mesg_maxlen);
1352         } else if (sync_state == IP_VS_STATE_BACKUP) {
1353                 dev = __dev_get_by_name(net, ipvs->backup_mcast_ifn);
1354                 if (!dev)
1355                         return -ENODEV;
1356
1357                 ipvs->recv_mesg_maxlen = dev->mtu -
1358                         sizeof(struct iphdr) - sizeof(struct udphdr);
1359                 IP_VS_DBG(7, "setting the maximum length of sync receiving "
1360                           "message %d.\n", ipvs->recv_mesg_maxlen);
1361         }
1362
1363         return 0;
1364 }
1365
1366
1367 /*
1368  *      Join a multicast group.
1369  *      the group is specified by a class D multicast address 224.0.0.0/8
1370  *      in the in_addr structure passed in as a parameter.
1371  */
1372 static int
1373 join_mcast_group(struct sock *sk, struct in_addr *addr, char *ifname)
1374 {
1375         struct net *net = sock_net(sk);
1376         struct ip_mreqn mreq;
1377         struct net_device *dev;
1378         int ret;
1379
1380         memset(&mreq, 0, sizeof(mreq));
1381         memcpy(&mreq.imr_multiaddr, addr, sizeof(struct in_addr));
1382
1383         dev = __dev_get_by_name(net, ifname);
1384         if (!dev)
1385                 return -ENODEV;
1386         if (sk->sk_bound_dev_if && dev->ifindex != sk->sk_bound_dev_if)
1387                 return -EINVAL;
1388
1389         mreq.imr_ifindex = dev->ifindex;
1390
1391         lock_sock(sk);
1392         ret = ip_mc_join_group(sk, &mreq);
1393         release_sock(sk);
1394
1395         return ret;
1396 }
1397
1398
1399 static int bind_mcastif_addr(struct socket *sock, char *ifname)
1400 {
1401         struct net *net = sock_net(sock->sk);
1402         struct net_device *dev;
1403         __be32 addr;
1404         struct sockaddr_in sin;
1405
1406         dev = __dev_get_by_name(net, ifname);
1407         if (!dev)
1408                 return -ENODEV;
1409
1410         addr = inet_select_addr(dev, 0, RT_SCOPE_UNIVERSE);
1411         if (!addr)
1412                 pr_err("You probably need to specify IP address on "
1413                        "multicast interface.\n");
1414
1415         IP_VS_DBG(7, "binding socket with (%s) %pI4\n",
1416                   ifname, &addr);
1417
1418         /* Now bind the socket with the address of multicast interface */
1419         sin.sin_family       = AF_INET;
1420         sin.sin_addr.s_addr  = addr;
1421         sin.sin_port         = 0;
1422
1423         return sock->ops->bind(sock, (struct sockaddr*)&sin, sizeof(sin));
1424 }
1425
1426 /*
1427  *      Set up sending multicast socket over UDP
1428  */
1429 static struct socket *make_send_sock(struct net *net, int id)
1430 {
1431         struct netns_ipvs *ipvs = net_ipvs(net);
1432         /* multicast addr */
1433         struct sockaddr_in mcast_addr = {
1434                 .sin_family             = AF_INET,
1435                 .sin_port               = cpu_to_be16(IP_VS_SYNC_PORT + id),
1436                 .sin_addr.s_addr        = cpu_to_be32(IP_VS_SYNC_GROUP),
1437         };
1438         struct socket *sock;
1439         int result;
1440
1441         /* First create a socket move it to right name space later */
1442         result = sock_create_kern(PF_INET, SOCK_DGRAM, IPPROTO_UDP, &sock);
1443         if (result < 0) {
1444                 pr_err("Error during creation of socket; terminating\n");
1445                 return ERR_PTR(result);
1446         }
1447         /*
1448          * Kernel sockets that are a part of a namespace, should not
1449          * hold a reference to a namespace in order to allow to stop it.
1450          * After sk_change_net should be released using sk_release_kernel.
1451          */
1452         sk_change_net(sock->sk, net);
1453         result = set_mcast_if(sock->sk, ipvs->master_mcast_ifn);
1454         if (result < 0) {
1455                 pr_err("Error setting outbound mcast interface\n");
1456                 goto error;
1457         }
1458
1459         set_mcast_loop(sock->sk, 0);
1460         set_mcast_ttl(sock->sk, 1);
1461         result = sysctl_sync_sock_size(ipvs);
1462         if (result > 0)
1463                 set_sock_size(sock->sk, 1, result);
1464
1465         result = bind_mcastif_addr(sock, ipvs->master_mcast_ifn);
1466         if (result < 0) {
1467                 pr_err("Error binding address of the mcast interface\n");
1468                 goto error;
1469         }
1470
1471         result = sock->ops->connect(sock, (struct sockaddr *) &mcast_addr,
1472                         sizeof(struct sockaddr), 0);
1473         if (result < 0) {
1474                 pr_err("Error connecting to the multicast addr\n");
1475                 goto error;
1476         }
1477
1478         return sock;
1479
1480 error:
1481         sk_release_kernel(sock->sk);
1482         return ERR_PTR(result);
1483 }
1484
1485
1486 /*
1487  *      Set up receiving multicast socket over UDP
1488  */
1489 static struct socket *make_receive_sock(struct net *net, int id)
1490 {
1491         struct netns_ipvs *ipvs = net_ipvs(net);
1492         /* multicast addr */
1493         struct sockaddr_in mcast_addr = {
1494                 .sin_family             = AF_INET,
1495                 .sin_port               = cpu_to_be16(IP_VS_SYNC_PORT + id),
1496                 .sin_addr.s_addr        = cpu_to_be32(IP_VS_SYNC_GROUP),
1497         };
1498         struct socket *sock;
1499         int result;
1500
1501         /* First create a socket */
1502         result = sock_create_kern(PF_INET, SOCK_DGRAM, IPPROTO_UDP, &sock);
1503         if (result < 0) {
1504                 pr_err("Error during creation of socket; terminating\n");
1505                 return ERR_PTR(result);
1506         }
1507         /*
1508          * Kernel sockets that are a part of a namespace, should not
1509          * hold a reference to a namespace in order to allow to stop it.
1510          * After sk_change_net should be released using sk_release_kernel.
1511          */
1512         sk_change_net(sock->sk, net);
1513         /* it is equivalent to the REUSEADDR option in user-space */
1514         sock->sk->sk_reuse = SK_CAN_REUSE;
1515         result = sysctl_sync_sock_size(ipvs);
1516         if (result > 0)
1517                 set_sock_size(sock->sk, 0, result);
1518
1519         result = sock->ops->bind(sock, (struct sockaddr *) &mcast_addr,
1520                         sizeof(struct sockaddr));
1521         if (result < 0) {
1522                 pr_err("Error binding to the multicast addr\n");
1523                 goto error;
1524         }
1525
1526         /* join the multicast group */
1527         result = join_mcast_group(sock->sk,
1528                         (struct in_addr *) &mcast_addr.sin_addr,
1529                         ipvs->backup_mcast_ifn);
1530         if (result < 0) {
1531                 pr_err("Error joining to the multicast group\n");
1532                 goto error;
1533         }
1534
1535         return sock;
1536
1537 error:
1538         sk_release_kernel(sock->sk);
1539         return ERR_PTR(result);
1540 }
1541
1542
1543 static int
1544 ip_vs_send_async(struct socket *sock, const char *buffer, const size_t length)
1545 {
1546         struct msghdr   msg = {.msg_flags = MSG_DONTWAIT|MSG_NOSIGNAL};
1547         struct kvec     iov;
1548         int             len;
1549
1550         EnterFunction(7);
1551         iov.iov_base     = (void *)buffer;
1552         iov.iov_len      = length;
1553
1554         len = kernel_sendmsg(sock, &msg, &iov, 1, (size_t)(length));
1555
1556         LeaveFunction(7);
1557         return len;
1558 }
1559
1560 static int
1561 ip_vs_send_sync_msg(struct socket *sock, struct ip_vs_sync_mesg *msg)
1562 {
1563         int msize;
1564         int ret;
1565
1566         msize = ntohs(msg->size);
1567
1568         ret = ip_vs_send_async(sock, (char *)msg, msize);
1569         if (ret >= 0 || ret == -EAGAIN)
1570                 return ret;
1571         pr_err("ip_vs_send_async error %d\n", ret);
1572         return 0;
1573 }
1574
1575 static int
1576 ip_vs_receive(struct socket *sock, char *buffer, const size_t buflen)
1577 {
1578         struct msghdr           msg = {NULL,};
1579         struct kvec             iov;
1580         int                     len;
1581
1582         EnterFunction(7);
1583
1584         /* Receive a packet */
1585         iov.iov_base     = buffer;
1586         iov.iov_len      = (size_t)buflen;
1587
1588         len = kernel_recvmsg(sock, &msg, &iov, 1, buflen, MSG_DONTWAIT);
1589
1590         if (len < 0)
1591                 return len;
1592
1593         LeaveFunction(7);
1594         return len;
1595 }
1596
1597 /* Wakeup the master thread for sending */
1598 static void master_wakeup_work_handler(struct work_struct *work)
1599 {
1600         struct ipvs_master_sync_state *ms =
1601                 container_of(work, struct ipvs_master_sync_state,
1602                              master_wakeup_work.work);
1603         struct netns_ipvs *ipvs = ms->ipvs;
1604
1605         spin_lock_bh(&ipvs->sync_lock);
1606         if (ms->sync_queue_len &&
1607             ms->sync_queue_delay < IPVS_SYNC_WAKEUP_RATE) {
1608                 ms->sync_queue_delay = IPVS_SYNC_WAKEUP_RATE;
1609                 wake_up_process(ms->master_thread);
1610         }
1611         spin_unlock_bh(&ipvs->sync_lock);
1612 }
1613
1614 /* Get next buffer to send */
1615 static inline struct ip_vs_sync_buff *
1616 next_sync_buff(struct netns_ipvs *ipvs, struct ipvs_master_sync_state *ms)
1617 {
1618         struct ip_vs_sync_buff *sb;
1619
1620         sb = sb_dequeue(ipvs, ms);
1621         if (sb)
1622                 return sb;
1623         /* Do not delay entries in buffer for more than 2 seconds */
1624         return get_curr_sync_buff(ipvs, ms, IPVS_SYNC_FLUSH_TIME);
1625 }
1626
1627 static int sync_thread_master(void *data)
1628 {
1629         struct ip_vs_sync_thread_data *tinfo = data;
1630         struct netns_ipvs *ipvs = net_ipvs(tinfo->net);
1631         struct ipvs_master_sync_state *ms = &ipvs->ms[tinfo->id];
1632         struct sock *sk = tinfo->sock->sk;
1633         struct ip_vs_sync_buff *sb;
1634
1635         pr_info("sync thread started: state = MASTER, mcast_ifn = %s, "
1636                 "syncid = %d, id = %d\n",
1637                 ipvs->master_mcast_ifn, ipvs->master_syncid, tinfo->id);
1638
1639         for (;;) {
1640                 sb = next_sync_buff(ipvs, ms);
1641                 if (unlikely(kthread_should_stop()))
1642                         break;
1643                 if (!sb) {
1644                         schedule_timeout(IPVS_SYNC_CHECK_PERIOD);
1645                         continue;
1646                 }
1647                 while (ip_vs_send_sync_msg(tinfo->sock, sb->mesg) < 0) {
1648                         /* (Ab)use interruptible sleep to avoid increasing
1649                          * the load avg.
1650                          */
1651                         __wait_event_interruptible(*sk_sleep(sk),
1652                                                    sock_writeable(sk) ||
1653                                                    kthread_should_stop());
1654                         if (unlikely(kthread_should_stop()))
1655                                 goto done;
1656                 }
1657                 ip_vs_sync_buff_release(sb);
1658         }
1659
1660 done:
1661         __set_current_state(TASK_RUNNING);
1662         if (sb)
1663                 ip_vs_sync_buff_release(sb);
1664
1665         /* clean up the sync_buff queue */
1666         while ((sb = sb_dequeue(ipvs, ms)))
1667                 ip_vs_sync_buff_release(sb);
1668         __set_current_state(TASK_RUNNING);
1669
1670         /* clean up the current sync_buff */
1671         sb = get_curr_sync_buff(ipvs, ms, 0);
1672         if (sb)
1673                 ip_vs_sync_buff_release(sb);
1674
1675         /* release the sending multicast socket */
1676         sk_release_kernel(tinfo->sock->sk);
1677         kfree(tinfo);
1678
1679         return 0;
1680 }
1681
1682
1683 static int sync_thread_backup(void *data)
1684 {
1685         struct ip_vs_sync_thread_data *tinfo = data;
1686         struct netns_ipvs *ipvs = net_ipvs(tinfo->net);
1687         int len;
1688
1689         pr_info("sync thread started: state = BACKUP, mcast_ifn = %s, "
1690                 "syncid = %d, id = %d\n",
1691                 ipvs->backup_mcast_ifn, ipvs->backup_syncid, tinfo->id);
1692
1693         while (!kthread_should_stop()) {
1694                 wait_event_interruptible(*sk_sleep(tinfo->sock->sk),
1695                          !skb_queue_empty(&tinfo->sock->sk->sk_receive_queue)
1696                          || kthread_should_stop());
1697
1698                 /* do we have data now? */
1699                 while (!skb_queue_empty(&(tinfo->sock->sk->sk_receive_queue))) {
1700                         len = ip_vs_receive(tinfo->sock, tinfo->buf,
1701                                         ipvs->recv_mesg_maxlen);
1702                         if (len <= 0) {
1703                                 if (len != -EAGAIN)
1704                                         pr_err("receiving message error\n");
1705                                 break;
1706                         }
1707
1708                         ip_vs_process_message(tinfo->net, tinfo->buf, len);
1709                 }
1710         }
1711
1712         /* release the sending multicast socket */
1713         sk_release_kernel(tinfo->sock->sk);
1714         kfree(tinfo->buf);
1715         kfree(tinfo);
1716
1717         return 0;
1718 }
1719
1720
1721 int start_sync_thread(struct net *net, int state, char *mcast_ifn, __u8 syncid)
1722 {
1723         struct ip_vs_sync_thread_data *tinfo;
1724         struct task_struct **array = NULL, *task;
1725         struct socket *sock;
1726         struct netns_ipvs *ipvs = net_ipvs(net);
1727         char *name;
1728         int (*threadfn)(void *data);
1729         int id, count;
1730         int result = -ENOMEM;
1731
1732         IP_VS_DBG(7, "%s(): pid %d\n", __func__, task_pid_nr(current));
1733         IP_VS_DBG(7, "Each ip_vs_sync_conn entry needs %Zd bytes\n",
1734                   sizeof(struct ip_vs_sync_conn_v0));
1735
1736         if (!ipvs->sync_state) {
1737                 count = clamp(sysctl_sync_ports(ipvs), 1, IPVS_SYNC_PORTS_MAX);
1738                 ipvs->threads_mask = count - 1;
1739         } else
1740                 count = ipvs->threads_mask + 1;
1741
1742         if (state == IP_VS_STATE_MASTER) {
1743                 if (ipvs->ms)
1744                         return -EEXIST;
1745
1746                 strlcpy(ipvs->master_mcast_ifn, mcast_ifn,
1747                         sizeof(ipvs->master_mcast_ifn));
1748                 ipvs->master_syncid = syncid;
1749                 name = "ipvs-m:%d:%d";
1750                 threadfn = sync_thread_master;
1751         } else if (state == IP_VS_STATE_BACKUP) {
1752                 if (ipvs->backup_threads)
1753                         return -EEXIST;
1754
1755                 strlcpy(ipvs->backup_mcast_ifn, mcast_ifn,
1756                         sizeof(ipvs->backup_mcast_ifn));
1757                 ipvs->backup_syncid = syncid;
1758                 name = "ipvs-b:%d:%d";
1759                 threadfn = sync_thread_backup;
1760         } else {
1761                 return -EINVAL;
1762         }
1763
1764         if (state == IP_VS_STATE_MASTER) {
1765                 struct ipvs_master_sync_state *ms;
1766
1767                 ipvs->ms = kzalloc(count * sizeof(ipvs->ms[0]), GFP_KERNEL);
1768                 if (!ipvs->ms)
1769                         goto out;
1770                 ms = ipvs->ms;
1771                 for (id = 0; id < count; id++, ms++) {
1772                         INIT_LIST_HEAD(&ms->sync_queue);
1773                         ms->sync_queue_len = 0;
1774                         ms->sync_queue_delay = 0;
1775                         INIT_DELAYED_WORK(&ms->master_wakeup_work,
1776                                           master_wakeup_work_handler);
1777                         ms->ipvs = ipvs;
1778                 }
1779         } else {
1780                 array = kzalloc(count * sizeof(struct task_struct *),
1781                                 GFP_KERNEL);
1782                 if (!array)
1783                         goto out;
1784         }
1785         set_sync_mesg_maxlen(net, state);
1786
1787         tinfo = NULL;
1788         for (id = 0; id < count; id++) {
1789                 if (state == IP_VS_STATE_MASTER)
1790                         sock = make_send_sock(net, id);
1791                 else
1792                         sock = make_receive_sock(net, id);
1793                 if (IS_ERR(sock)) {
1794                         result = PTR_ERR(sock);
1795                         goto outtinfo;
1796                 }
1797                 tinfo = kmalloc(sizeof(*tinfo), GFP_KERNEL);
1798                 if (!tinfo)
1799                         goto outsocket;
1800                 tinfo->net = net;
1801                 tinfo->sock = sock;
1802                 if (state == IP_VS_STATE_BACKUP) {
1803                         tinfo->buf = kmalloc(ipvs->recv_mesg_maxlen,
1804                                              GFP_KERNEL);
1805                         if (!tinfo->buf)
1806                                 goto outtinfo;
1807                 } else {
1808                         tinfo->buf = NULL;
1809                 }
1810                 tinfo->id = id;
1811
1812                 task = kthread_run(threadfn, tinfo, name, ipvs->gen, id);
1813                 if (IS_ERR(task)) {
1814                         result = PTR_ERR(task);
1815                         goto outtinfo;
1816                 }
1817                 tinfo = NULL;
1818                 if (state == IP_VS_STATE_MASTER)
1819                         ipvs->ms[id].master_thread = task;
1820                 else
1821                         array[id] = task;
1822         }
1823
1824         /* mark as active */
1825
1826         if (state == IP_VS_STATE_BACKUP)
1827                 ipvs->backup_threads = array;
1828         spin_lock_bh(&ipvs->sync_buff_lock);
1829         ipvs->sync_state |= state;
1830         spin_unlock_bh(&ipvs->sync_buff_lock);
1831
1832         /* increase the module use count */
1833         ip_vs_use_count_inc();
1834
1835         return 0;
1836
1837 outsocket:
1838         sk_release_kernel(sock->sk);
1839
1840 outtinfo:
1841         if (tinfo) {
1842                 sk_release_kernel(tinfo->sock->sk);
1843                 kfree(tinfo->buf);
1844                 kfree(tinfo);
1845         }
1846         count = id;
1847         while (count-- > 0) {
1848                 if (state == IP_VS_STATE_MASTER)
1849                         kthread_stop(ipvs->ms[count].master_thread);
1850                 else
1851                         kthread_stop(array[count]);
1852         }
1853         kfree(array);
1854
1855 out:
1856         if (!(ipvs->sync_state & IP_VS_STATE_MASTER)) {
1857                 kfree(ipvs->ms);
1858                 ipvs->ms = NULL;
1859         }
1860         return result;
1861 }
1862
1863
1864 int stop_sync_thread(struct net *net, int state)
1865 {
1866         struct netns_ipvs *ipvs = net_ipvs(net);
1867         struct task_struct **array;
1868         int id;
1869         int retc = -EINVAL;
1870
1871         IP_VS_DBG(7, "%s(): pid %d\n", __func__, task_pid_nr(current));
1872
1873         if (state == IP_VS_STATE_MASTER) {
1874                 if (!ipvs->ms)
1875                         return -ESRCH;
1876
1877                 /*
1878                  * The lock synchronizes with sb_queue_tail(), so that we don't
1879                  * add sync buffers to the queue, when we are already in
1880                  * progress of stopping the master sync daemon.
1881                  */
1882
1883                 spin_lock_bh(&ipvs->sync_buff_lock);
1884                 spin_lock(&ipvs->sync_lock);
1885                 ipvs->sync_state &= ~IP_VS_STATE_MASTER;
1886                 spin_unlock(&ipvs->sync_lock);
1887                 spin_unlock_bh(&ipvs->sync_buff_lock);
1888
1889                 retc = 0;
1890                 for (id = ipvs->threads_mask; id >= 0; id--) {
1891                         struct ipvs_master_sync_state *ms = &ipvs->ms[id];
1892                         int ret;
1893
1894                         pr_info("stopping master sync thread %d ...\n",
1895                                 task_pid_nr(ms->master_thread));
1896                         cancel_delayed_work_sync(&ms->master_wakeup_work);
1897                         ret = kthread_stop(ms->master_thread);
1898                         if (retc >= 0)
1899                                 retc = ret;
1900                 }
1901                 kfree(ipvs->ms);
1902                 ipvs->ms = NULL;
1903         } else if (state == IP_VS_STATE_BACKUP) {
1904                 if (!ipvs->backup_threads)
1905                         return -ESRCH;
1906
1907                 ipvs->sync_state &= ~IP_VS_STATE_BACKUP;
1908                 array = ipvs->backup_threads;
1909                 retc = 0;
1910                 for (id = ipvs->threads_mask; id >= 0; id--) {
1911                         int ret;
1912
1913                         pr_info("stopping backup sync thread %d ...\n",
1914                                 task_pid_nr(array[id]));
1915                         ret = kthread_stop(array[id]);
1916                         if (retc >= 0)
1917                                 retc = ret;
1918                 }
1919                 kfree(array);
1920                 ipvs->backup_threads = NULL;
1921         }
1922
1923         /* decrease the module use count */
1924         ip_vs_use_count_dec();
1925
1926         return retc;
1927 }
1928
1929 /*
1930  * Initialize data struct for each netns
1931  */
1932 int __net_init ip_vs_sync_net_init(struct net *net)
1933 {
1934         struct netns_ipvs *ipvs = net_ipvs(net);
1935
1936         __mutex_init(&ipvs->sync_mutex, "ipvs->sync_mutex", &__ipvs_sync_key);
1937         spin_lock_init(&ipvs->sync_lock);
1938         spin_lock_init(&ipvs->sync_buff_lock);
1939         return 0;
1940 }
1941
1942 void ip_vs_sync_net_cleanup(struct net *net)
1943 {
1944         int retc;
1945         struct netns_ipvs *ipvs = net_ipvs(net);
1946
1947         mutex_lock(&ipvs->sync_mutex);
1948         retc = stop_sync_thread(net, IP_VS_STATE_MASTER);
1949         if (retc && retc != -ESRCH)
1950                 pr_err("Failed to stop Master Daemon\n");
1951
1952         retc = stop_sync_thread(net, IP_VS_STATE_BACKUP);
1953         if (retc && retc != -ESRCH)
1954                 pr_err("Failed to stop Backup Daemon\n");
1955         mutex_unlock(&ipvs->sync_mutex);
1956 }