ipvs: replace the SCTP state machine
[firefly-linux-kernel-4.4.55.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 conn should be synced.
429  * pkts: conn packets, use sysctl_sync_threshold to avoid packet check
430  * - (1) sync_refresh_period: reduce sync rate. Additionally, retry
431  *      sync_retries times with period of sync_refresh_period/8
432  * - (2) if both sync_refresh_period and sync_period are 0 send sync only
433  *      for state changes or only once when pkts matches sync_threshold
434  * - (3) templates: rate can be reduced only with sync_refresh_period or
435  *      with (2)
436  */
437 static int ip_vs_sync_conn_needed(struct netns_ipvs *ipvs,
438                                   struct ip_vs_conn *cp, int pkts)
439 {
440         unsigned long orig = ACCESS_ONCE(cp->sync_endtime);
441         unsigned long now = jiffies;
442         unsigned long n = (now + cp->timeout) & ~3UL;
443         unsigned int sync_refresh_period;
444         int sync_period;
445         int force;
446
447         /* Check if we sync in current state */
448         if (unlikely(cp->flags & IP_VS_CONN_F_TEMPLATE))
449                 force = 0;
450         else if (likely(cp->protocol == IPPROTO_TCP)) {
451                 if (!((1 << cp->state) &
452                       ((1 << IP_VS_TCP_S_ESTABLISHED) |
453                        (1 << IP_VS_TCP_S_FIN_WAIT) |
454                        (1 << IP_VS_TCP_S_CLOSE) |
455                        (1 << IP_VS_TCP_S_CLOSE_WAIT) |
456                        (1 << IP_VS_TCP_S_TIME_WAIT))))
457                         return 0;
458                 force = cp->state != cp->old_state;
459                 if (force && cp->state != IP_VS_TCP_S_ESTABLISHED)
460                         goto set;
461         } else if (unlikely(cp->protocol == IPPROTO_SCTP)) {
462                 if (!((1 << cp->state) &
463                       ((1 << IP_VS_SCTP_S_ESTABLISHED) |
464                        (1 << IP_VS_SCTP_S_SHUTDOWN_SENT) |
465                        (1 << IP_VS_SCTP_S_SHUTDOWN_RECEIVED) |
466                        (1 << IP_VS_SCTP_S_SHUTDOWN_ACK_SENT) |
467                        (1 << IP_VS_SCTP_S_CLOSED))))
468                         return 0;
469                 force = cp->state != cp->old_state;
470                 if (force && cp->state != IP_VS_SCTP_S_ESTABLISHED)
471                         goto set;
472         } else {
473                 /* UDP or another protocol with single state */
474                 force = 0;
475         }
476
477         sync_refresh_period = sysctl_sync_refresh_period(ipvs);
478         if (sync_refresh_period > 0) {
479                 long diff = n - orig;
480                 long min_diff = max(cp->timeout >> 1, 10UL * HZ);
481
482                 /* Avoid sync if difference is below sync_refresh_period
483                  * and below the half timeout.
484                  */
485                 if (abs(diff) < min_t(long, sync_refresh_period, min_diff)) {
486                         int retries = orig & 3;
487
488                         if (retries >= sysctl_sync_retries(ipvs))
489                                 return 0;
490                         if (time_before(now, orig - cp->timeout +
491                                         (sync_refresh_period >> 3)))
492                                 return 0;
493                         n |= retries + 1;
494                 }
495         }
496         sync_period = sysctl_sync_period(ipvs);
497         if (sync_period > 0) {
498                 if (!(cp->flags & IP_VS_CONN_F_TEMPLATE) &&
499                     pkts % sync_period != sysctl_sync_threshold(ipvs))
500                         return 0;
501         } else if (sync_refresh_period <= 0 &&
502                    pkts != sysctl_sync_threshold(ipvs))
503                 return 0;
504
505 set:
506         cp->old_state = cp->state;
507         n = cmpxchg(&cp->sync_endtime, orig, n);
508         return n == orig || force;
509 }
510
511 /*
512  *      Version 0 , could be switched in by sys_ctl.
513  *      Add an ip_vs_conn information into the current sync_buff.
514  */
515 static void ip_vs_sync_conn_v0(struct net *net, struct ip_vs_conn *cp,
516                                int pkts)
517 {
518         struct netns_ipvs *ipvs = net_ipvs(net);
519         struct ip_vs_sync_mesg_v0 *m;
520         struct ip_vs_sync_conn_v0 *s;
521         struct ip_vs_sync_buff *buff;
522         struct ipvs_master_sync_state *ms;
523         int id;
524         int len;
525
526         if (unlikely(cp->af != AF_INET))
527                 return;
528         /* Do not sync ONE PACKET */
529         if (cp->flags & IP_VS_CONN_F_ONE_PACKET)
530                 return;
531
532         if (!ip_vs_sync_conn_needed(ipvs, cp, pkts))
533                 return;
534
535         spin_lock_bh(&ipvs->sync_buff_lock);
536         if (!(ipvs->sync_state & IP_VS_STATE_MASTER)) {
537                 spin_unlock_bh(&ipvs->sync_buff_lock);
538                 return;
539         }
540
541         id = select_master_thread_id(ipvs, cp);
542         ms = &ipvs->ms[id];
543         buff = ms->sync_buff;
544         if (buff) {
545                 m = (struct ip_vs_sync_mesg_v0 *) buff->mesg;
546                 /* Send buffer if it is for v1 */
547                 if (!m->nr_conns) {
548                         sb_queue_tail(ipvs, ms);
549                         ms->sync_buff = NULL;
550                         buff = NULL;
551                 }
552         }
553         if (!buff) {
554                 buff = ip_vs_sync_buff_create_v0(ipvs);
555                 if (!buff) {
556                         spin_unlock_bh(&ipvs->sync_buff_lock);
557                         pr_err("ip_vs_sync_buff_create failed.\n");
558                         return;
559                 }
560                 ms->sync_buff = buff;
561         }
562
563         len = (cp->flags & IP_VS_CONN_F_SEQ_MASK) ? FULL_CONN_SIZE :
564                 SIMPLE_CONN_SIZE;
565         m = (struct ip_vs_sync_mesg_v0 *) buff->mesg;
566         s = (struct ip_vs_sync_conn_v0 *) buff->head;
567
568         /* copy members */
569         s->reserved = 0;
570         s->protocol = cp->protocol;
571         s->cport = cp->cport;
572         s->vport = cp->vport;
573         s->dport = cp->dport;
574         s->caddr = cp->caddr.ip;
575         s->vaddr = cp->vaddr.ip;
576         s->daddr = cp->daddr.ip;
577         s->flags = htons(cp->flags & ~IP_VS_CONN_F_HASHED);
578         s->state = htons(cp->state);
579         if (cp->flags & IP_VS_CONN_F_SEQ_MASK) {
580                 struct ip_vs_sync_conn_options *opt =
581                         (struct ip_vs_sync_conn_options *)&s[1];
582                 memcpy(opt, &cp->in_seq, sizeof(*opt));
583         }
584
585         m->nr_conns++;
586         m->size = htons(ntohs(m->size) + len);
587         buff->head += len;
588
589         /* check if there is a space for next one */
590         if (buff->head + FULL_CONN_SIZE > buff->end) {
591                 sb_queue_tail(ipvs, ms);
592                 ms->sync_buff = NULL;
593         }
594         spin_unlock_bh(&ipvs->sync_buff_lock);
595
596         /* synchronize its controller if it has */
597         cp = cp->control;
598         if (cp) {
599                 if (cp->flags & IP_VS_CONN_F_TEMPLATE)
600                         pkts = atomic_add_return(1, &cp->in_pkts);
601                 else
602                         pkts = sysctl_sync_threshold(ipvs);
603                 ip_vs_sync_conn(net, cp->control, pkts);
604         }
605 }
606
607 /*
608  *      Add an ip_vs_conn information into the current sync_buff.
609  *      Called by ip_vs_in.
610  *      Sending Version 1 messages
611  */
612 void ip_vs_sync_conn(struct net *net, struct ip_vs_conn *cp, int pkts)
613 {
614         struct netns_ipvs *ipvs = net_ipvs(net);
615         struct ip_vs_sync_mesg *m;
616         union ip_vs_sync_conn *s;
617         struct ip_vs_sync_buff *buff;
618         struct ipvs_master_sync_state *ms;
619         int id;
620         __u8 *p;
621         unsigned int len, pe_name_len, pad;
622
623         /* Handle old version of the protocol */
624         if (sysctl_sync_ver(ipvs) == 0) {
625                 ip_vs_sync_conn_v0(net, cp, pkts);
626                 return;
627         }
628         /* Do not sync ONE PACKET */
629         if (cp->flags & IP_VS_CONN_F_ONE_PACKET)
630                 goto control;
631 sloop:
632         if (!ip_vs_sync_conn_needed(ipvs, cp, pkts))
633                 goto control;
634
635         /* Sanity checks */
636         pe_name_len = 0;
637         if (cp->pe_data_len) {
638                 if (!cp->pe_data || !cp->dest) {
639                         IP_VS_ERR_RL("SYNC, connection pe_data invalid\n");
640                         return;
641                 }
642                 pe_name_len = strnlen(cp->pe->name, IP_VS_PENAME_MAXLEN);
643         }
644
645         spin_lock_bh(&ipvs->sync_buff_lock);
646         if (!(ipvs->sync_state & IP_VS_STATE_MASTER)) {
647                 spin_unlock_bh(&ipvs->sync_buff_lock);
648                 return;
649         }
650
651         id = select_master_thread_id(ipvs, cp);
652         ms = &ipvs->ms[id];
653
654 #ifdef CONFIG_IP_VS_IPV6
655         if (cp->af == AF_INET6)
656                 len = sizeof(struct ip_vs_sync_v6);
657         else
658 #endif
659                 len = sizeof(struct ip_vs_sync_v4);
660
661         if (cp->flags & IP_VS_CONN_F_SEQ_MASK)
662                 len += sizeof(struct ip_vs_sync_conn_options) + 2;
663
664         if (cp->pe_data_len)
665                 len += cp->pe_data_len + 2;     /* + Param hdr field */
666         if (pe_name_len)
667                 len += pe_name_len + 2;
668
669         /* check if there is a space for this one  */
670         pad = 0;
671         buff = ms->sync_buff;
672         if (buff) {
673                 m = buff->mesg;
674                 pad = (4 - (size_t) buff->head) & 3;
675                 /* Send buffer if it is for v0 */
676                 if (buff->head + len + pad > buff->end || m->reserved) {
677                         sb_queue_tail(ipvs, ms);
678                         ms->sync_buff = NULL;
679                         buff = NULL;
680                         pad = 0;
681                 }
682         }
683
684         if (!buff) {
685                 buff = ip_vs_sync_buff_create(ipvs);
686                 if (!buff) {
687                         spin_unlock_bh(&ipvs->sync_buff_lock);
688                         pr_err("ip_vs_sync_buff_create failed.\n");
689                         return;
690                 }
691                 ms->sync_buff = buff;
692                 m = buff->mesg;
693         }
694
695         p = buff->head;
696         buff->head += pad + len;
697         m->size = htons(ntohs(m->size) + pad + len);
698         /* Add ev. padding from prev. sync_conn */
699         while (pad--)
700                 *(p++) = 0;
701
702         s = (union ip_vs_sync_conn *)p;
703
704         /* Set message type  & copy members */
705         s->v4.type = (cp->af == AF_INET6 ? STYPE_F_INET6 : 0);
706         s->v4.ver_size = htons(len & SVER_MASK);        /* Version 0 */
707         s->v4.flags = htonl(cp->flags & ~IP_VS_CONN_F_HASHED);
708         s->v4.state = htons(cp->state);
709         s->v4.protocol = cp->protocol;
710         s->v4.cport = cp->cport;
711         s->v4.vport = cp->vport;
712         s->v4.dport = cp->dport;
713         s->v4.fwmark = htonl(cp->fwmark);
714         s->v4.timeout = htonl(cp->timeout / HZ);
715         m->nr_conns++;
716
717 #ifdef CONFIG_IP_VS_IPV6
718         if (cp->af == AF_INET6) {
719                 p += sizeof(struct ip_vs_sync_v6);
720                 s->v6.caddr = cp->caddr.in6;
721                 s->v6.vaddr = cp->vaddr.in6;
722                 s->v6.daddr = cp->daddr.in6;
723         } else
724 #endif
725         {
726                 p += sizeof(struct ip_vs_sync_v4);      /* options ptr */
727                 s->v4.caddr = cp->caddr.ip;
728                 s->v4.vaddr = cp->vaddr.ip;
729                 s->v4.daddr = cp->daddr.ip;
730         }
731         if (cp->flags & IP_VS_CONN_F_SEQ_MASK) {
732                 *(p++) = IPVS_OPT_SEQ_DATA;
733                 *(p++) = sizeof(struct ip_vs_sync_conn_options);
734                 hton_seq((struct ip_vs_seq *)p, &cp->in_seq);
735                 p += sizeof(struct ip_vs_seq);
736                 hton_seq((struct ip_vs_seq *)p, &cp->out_seq);
737                 p += sizeof(struct ip_vs_seq);
738         }
739         /* Handle pe data */
740         if (cp->pe_data_len && cp->pe_data) {
741                 *(p++) = IPVS_OPT_PE_DATA;
742                 *(p++) = cp->pe_data_len;
743                 memcpy(p, cp->pe_data, cp->pe_data_len);
744                 p += cp->pe_data_len;
745                 if (pe_name_len) {
746                         /* Add PE_NAME */
747                         *(p++) = IPVS_OPT_PE_NAME;
748                         *(p++) = pe_name_len;
749                         memcpy(p, cp->pe->name, pe_name_len);
750                         p += pe_name_len;
751                 }
752         }
753
754         spin_unlock_bh(&ipvs->sync_buff_lock);
755
756 control:
757         /* synchronize its controller if it has */
758         cp = cp->control;
759         if (!cp)
760                 return;
761         if (cp->flags & IP_VS_CONN_F_TEMPLATE)
762                 pkts = atomic_add_return(1, &cp->in_pkts);
763         else
764                 pkts = sysctl_sync_threshold(ipvs);
765         goto sloop;
766 }
767
768 /*
769  *  fill_param used by version 1
770  */
771 static inline int
772 ip_vs_conn_fill_param_sync(struct net *net, int af, union ip_vs_sync_conn *sc,
773                            struct ip_vs_conn_param *p,
774                            __u8 *pe_data, unsigned int pe_data_len,
775                            __u8 *pe_name, unsigned int pe_name_len)
776 {
777 #ifdef CONFIG_IP_VS_IPV6
778         if (af == AF_INET6)
779                 ip_vs_conn_fill_param(net, af, sc->v6.protocol,
780                                       (const union nf_inet_addr *)&sc->v6.caddr,
781                                       sc->v6.cport,
782                                       (const union nf_inet_addr *)&sc->v6.vaddr,
783                                       sc->v6.vport, p);
784         else
785 #endif
786                 ip_vs_conn_fill_param(net, af, sc->v4.protocol,
787                                       (const union nf_inet_addr *)&sc->v4.caddr,
788                                       sc->v4.cport,
789                                       (const union nf_inet_addr *)&sc->v4.vaddr,
790                                       sc->v4.vport, p);
791         /* Handle pe data */
792         if (pe_data_len) {
793                 if (pe_name_len) {
794                         char buff[IP_VS_PENAME_MAXLEN+1];
795
796                         memcpy(buff, pe_name, pe_name_len);
797                         buff[pe_name_len]=0;
798                         p->pe = __ip_vs_pe_getbyname(buff);
799                         if (!p->pe) {
800                                 IP_VS_DBG(3, "BACKUP, no %s engine found/loaded\n",
801                                              buff);
802                                 return 1;
803                         }
804                 } else {
805                         IP_VS_ERR_RL("BACKUP, Invalid PE parameters\n");
806                         return 1;
807                 }
808
809                 p->pe_data = kmemdup(pe_data, pe_data_len, GFP_ATOMIC);
810                 if (!p->pe_data) {
811                         if (p->pe->module)
812                                 module_put(p->pe->module);
813                         return -ENOMEM;
814                 }
815                 p->pe_data_len = pe_data_len;
816         }
817         return 0;
818 }
819
820 /*
821  *  Connection Add / Update.
822  *  Common for version 0 and 1 reception of backup sync_conns.
823  *  Param: ...
824  *         timeout is in sec.
825  */
826 static void ip_vs_proc_conn(struct net *net, struct ip_vs_conn_param *param,
827                             unsigned int flags, unsigned int state,
828                             unsigned int protocol, unsigned int type,
829                             const union nf_inet_addr *daddr, __be16 dport,
830                             unsigned long timeout, __u32 fwmark,
831                             struct ip_vs_sync_conn_options *opt)
832 {
833         struct ip_vs_dest *dest;
834         struct ip_vs_conn *cp;
835         struct netns_ipvs *ipvs = net_ipvs(net);
836
837         if (!(flags & IP_VS_CONN_F_TEMPLATE))
838                 cp = ip_vs_conn_in_get(param);
839         else
840                 cp = ip_vs_ct_in_get(param);
841
842         if (cp) {
843                 /* Free pe_data */
844                 kfree(param->pe_data);
845
846                 dest = cp->dest;
847                 spin_lock_bh(&cp->lock);
848                 if ((cp->flags ^ flags) & IP_VS_CONN_F_INACTIVE &&
849                     !(flags & IP_VS_CONN_F_TEMPLATE) && dest) {
850                         if (flags & IP_VS_CONN_F_INACTIVE) {
851                                 atomic_dec(&dest->activeconns);
852                                 atomic_inc(&dest->inactconns);
853                         } else {
854                                 atomic_inc(&dest->activeconns);
855                                 atomic_dec(&dest->inactconns);
856                         }
857                 }
858                 flags &= IP_VS_CONN_F_BACKUP_UPD_MASK;
859                 flags |= cp->flags & ~IP_VS_CONN_F_BACKUP_UPD_MASK;
860                 cp->flags = flags;
861                 spin_unlock_bh(&cp->lock);
862                 if (!dest)
863                         ip_vs_try_bind_dest(cp);
864         } else {
865                 /*
866                  * Find the appropriate destination for the connection.
867                  * If it is not found the connection will remain unbound
868                  * but still handled.
869                  */
870                 rcu_read_lock();
871                 dest = ip_vs_find_dest(net, type, daddr, dport, param->vaddr,
872                                        param->vport, protocol, fwmark, flags);
873
874                 cp = ip_vs_conn_new(param, daddr, dport, flags, dest, fwmark);
875                 rcu_read_unlock();
876                 if (!cp) {
877                         if (param->pe_data)
878                                 kfree(param->pe_data);
879                         IP_VS_DBG(2, "BACKUP, add new conn. failed\n");
880                         return;
881                 }
882         }
883
884         if (opt)
885                 memcpy(&cp->in_seq, opt, sizeof(*opt));
886         atomic_set(&cp->in_pkts, sysctl_sync_threshold(ipvs));
887         cp->state = state;
888         cp->old_state = cp->state;
889         /*
890          * For Ver 0 messages style
891          *  - Not possible to recover the right timeout for templates
892          *  - can not find the right fwmark
893          *    virtual service. If needed, we can do it for
894          *    non-fwmark persistent services.
895          * Ver 1 messages style.
896          *  - No problem.
897          */
898         if (timeout) {
899                 if (timeout > MAX_SCHEDULE_TIMEOUT / HZ)
900                         timeout = MAX_SCHEDULE_TIMEOUT / HZ;
901                 cp->timeout = timeout*HZ;
902         } else {
903                 struct ip_vs_proto_data *pd;
904
905                 pd = ip_vs_proto_data_get(net, protocol);
906                 if (!(flags & IP_VS_CONN_F_TEMPLATE) && pd && pd->timeout_table)
907                         cp->timeout = pd->timeout_table[state];
908                 else
909                         cp->timeout = (3*60*HZ);
910         }
911         ip_vs_conn_put(cp);
912 }
913
914 /*
915  *  Process received multicast message for Version 0
916  */
917 static void ip_vs_process_message_v0(struct net *net, const char *buffer,
918                                      const size_t buflen)
919 {
920         struct ip_vs_sync_mesg_v0 *m = (struct ip_vs_sync_mesg_v0 *)buffer;
921         struct ip_vs_sync_conn_v0 *s;
922         struct ip_vs_sync_conn_options *opt;
923         struct ip_vs_protocol *pp;
924         struct ip_vs_conn_param param;
925         char *p;
926         int i;
927
928         p = (char *)buffer + sizeof(struct ip_vs_sync_mesg_v0);
929         for (i=0; i<m->nr_conns; i++) {
930                 unsigned int flags, state;
931
932                 if (p + SIMPLE_CONN_SIZE > buffer+buflen) {
933                         IP_VS_ERR_RL("BACKUP v0, bogus conn\n");
934                         return;
935                 }
936                 s = (struct ip_vs_sync_conn_v0 *) p;
937                 flags = ntohs(s->flags) | IP_VS_CONN_F_SYNC;
938                 flags &= ~IP_VS_CONN_F_HASHED;
939                 if (flags & IP_VS_CONN_F_SEQ_MASK) {
940                         opt = (struct ip_vs_sync_conn_options *)&s[1];
941                         p += FULL_CONN_SIZE;
942                         if (p > buffer+buflen) {
943                                 IP_VS_ERR_RL("BACKUP v0, Dropping buffer bogus conn options\n");
944                                 return;
945                         }
946                 } else {
947                         opt = NULL;
948                         p += SIMPLE_CONN_SIZE;
949                 }
950
951                 state = ntohs(s->state);
952                 if (!(flags & IP_VS_CONN_F_TEMPLATE)) {
953                         pp = ip_vs_proto_get(s->protocol);
954                         if (!pp) {
955                                 IP_VS_DBG(2, "BACKUP v0, Unsupported protocol %u\n",
956                                         s->protocol);
957                                 continue;
958                         }
959                         if (state >= pp->num_states) {
960                                 IP_VS_DBG(2, "BACKUP v0, Invalid %s state %u\n",
961                                         pp->name, state);
962                                 continue;
963                         }
964                 } else {
965                         /* protocol in templates is not used for state/timeout */
966                         if (state > 0) {
967                                 IP_VS_DBG(2, "BACKUP v0, Invalid template state %u\n",
968                                         state);
969                                 state = 0;
970                         }
971                 }
972
973                 ip_vs_conn_fill_param(net, AF_INET, s->protocol,
974                                       (const union nf_inet_addr *)&s->caddr,
975                                       s->cport,
976                                       (const union nf_inet_addr *)&s->vaddr,
977                                       s->vport, &param);
978
979                 /* Send timeout as Zero */
980                 ip_vs_proc_conn(net, &param, flags, state, s->protocol, AF_INET,
981                                 (union nf_inet_addr *)&s->daddr, s->dport,
982                                 0, 0, opt);
983         }
984 }
985
986 /*
987  * Handle options
988  */
989 static inline int ip_vs_proc_seqopt(__u8 *p, unsigned int plen,
990                                     __u32 *opt_flags,
991                                     struct ip_vs_sync_conn_options *opt)
992 {
993         struct ip_vs_sync_conn_options *topt;
994
995         topt = (struct ip_vs_sync_conn_options *)p;
996
997         if (plen != sizeof(struct ip_vs_sync_conn_options)) {
998                 IP_VS_DBG(2, "BACKUP, bogus conn options length\n");
999                 return -EINVAL;
1000         }
1001         if (*opt_flags & IPVS_OPT_F_SEQ_DATA) {
1002                 IP_VS_DBG(2, "BACKUP, conn options found twice\n");
1003                 return -EINVAL;
1004         }
1005         ntoh_seq(&topt->in_seq, &opt->in_seq);
1006         ntoh_seq(&topt->out_seq, &opt->out_seq);
1007         *opt_flags |= IPVS_OPT_F_SEQ_DATA;
1008         return 0;
1009 }
1010
1011 static int ip_vs_proc_str(__u8 *p, unsigned int plen, unsigned int *data_len,
1012                           __u8 **data, unsigned int maxlen,
1013                           __u32 *opt_flags, __u32 flag)
1014 {
1015         if (plen > maxlen) {
1016                 IP_VS_DBG(2, "BACKUP, bogus par.data len > %d\n", maxlen);
1017                 return -EINVAL;
1018         }
1019         if (*opt_flags & flag) {
1020                 IP_VS_DBG(2, "BACKUP, Par.data found twice 0x%x\n", flag);
1021                 return -EINVAL;
1022         }
1023         *data_len = plen;
1024         *data = p;
1025         *opt_flags |= flag;
1026         return 0;
1027 }
1028 /*
1029  *   Process a Version 1 sync. connection
1030  */
1031 static inline int ip_vs_proc_sync_conn(struct net *net, __u8 *p, __u8 *msg_end)
1032 {
1033         struct ip_vs_sync_conn_options opt;
1034         union  ip_vs_sync_conn *s;
1035         struct ip_vs_protocol *pp;
1036         struct ip_vs_conn_param param;
1037         __u32 flags;
1038         unsigned int af, state, pe_data_len=0, pe_name_len=0;
1039         __u8 *pe_data=NULL, *pe_name=NULL;
1040         __u32 opt_flags=0;
1041         int retc=0;
1042
1043         s = (union ip_vs_sync_conn *) p;
1044
1045         if (s->v6.type & STYPE_F_INET6) {
1046 #ifdef CONFIG_IP_VS_IPV6
1047                 af = AF_INET6;
1048                 p += sizeof(struct ip_vs_sync_v6);
1049 #else
1050                 IP_VS_DBG(3,"BACKUP, IPv6 msg received, and IPVS is not compiled for IPv6\n");
1051                 retc = 10;
1052                 goto out;
1053 #endif
1054         } else if (!s->v4.type) {
1055                 af = AF_INET;
1056                 p += sizeof(struct ip_vs_sync_v4);
1057         } else {
1058                 return -10;
1059         }
1060         if (p > msg_end)
1061                 return -20;
1062
1063         /* Process optional params check Type & Len. */
1064         while (p < msg_end) {
1065                 int ptype;
1066                 int plen;
1067
1068                 if (p+2 > msg_end)
1069                         return -30;
1070                 ptype = *(p++);
1071                 plen  = *(p++);
1072
1073                 if (!plen || ((p + plen) > msg_end))
1074                         return -40;
1075                 /* Handle seq option  p = param data */
1076                 switch (ptype & ~IPVS_OPT_F_PARAM) {
1077                 case IPVS_OPT_SEQ_DATA:
1078                         if (ip_vs_proc_seqopt(p, plen, &opt_flags, &opt))
1079                                 return -50;
1080                         break;
1081
1082                 case IPVS_OPT_PE_DATA:
1083                         if (ip_vs_proc_str(p, plen, &pe_data_len, &pe_data,
1084                                            IP_VS_PEDATA_MAXLEN, &opt_flags,
1085                                            IPVS_OPT_F_PE_DATA))
1086                                 return -60;
1087                         break;
1088
1089                 case IPVS_OPT_PE_NAME:
1090                         if (ip_vs_proc_str(p, plen,&pe_name_len, &pe_name,
1091                                            IP_VS_PENAME_MAXLEN, &opt_flags,
1092                                            IPVS_OPT_F_PE_NAME))
1093                                 return -70;
1094                         break;
1095
1096                 default:
1097                         /* Param data mandatory ? */
1098                         if (!(ptype & IPVS_OPT_F_PARAM)) {
1099                                 IP_VS_DBG(3, "BACKUP, Unknown mandatory param %d found\n",
1100                                           ptype & ~IPVS_OPT_F_PARAM);
1101                                 retc = 20;
1102                                 goto out;
1103                         }
1104                 }
1105                 p += plen;  /* Next option */
1106         }
1107
1108         /* Get flags and Mask off unsupported */
1109         flags  = ntohl(s->v4.flags) & IP_VS_CONN_F_BACKUP_MASK;
1110         flags |= IP_VS_CONN_F_SYNC;
1111         state = ntohs(s->v4.state);
1112
1113         if (!(flags & IP_VS_CONN_F_TEMPLATE)) {
1114                 pp = ip_vs_proto_get(s->v4.protocol);
1115                 if (!pp) {
1116                         IP_VS_DBG(3,"BACKUP, Unsupported protocol %u\n",
1117                                 s->v4.protocol);
1118                         retc = 30;
1119                         goto out;
1120                 }
1121                 if (state >= pp->num_states) {
1122                         IP_VS_DBG(3, "BACKUP, Invalid %s state %u\n",
1123                                 pp->name, state);
1124                         retc = 40;
1125                         goto out;
1126                 }
1127         } else {
1128                 /* protocol in templates is not used for state/timeout */
1129                 if (state > 0) {
1130                         IP_VS_DBG(3, "BACKUP, Invalid template state %u\n",
1131                                 state);
1132                         state = 0;
1133                 }
1134         }
1135         if (ip_vs_conn_fill_param_sync(net, af, s, &param, pe_data,
1136                                        pe_data_len, pe_name, pe_name_len)) {
1137                 retc = 50;
1138                 goto out;
1139         }
1140         /* If only IPv4, just silent skip IPv6 */
1141         if (af == AF_INET)
1142                 ip_vs_proc_conn(net, &param, flags, state, s->v4.protocol, af,
1143                                 (union nf_inet_addr *)&s->v4.daddr, s->v4.dport,
1144                                 ntohl(s->v4.timeout), ntohl(s->v4.fwmark),
1145                                 (opt_flags & IPVS_OPT_F_SEQ_DATA ? &opt : NULL)
1146                                 );
1147 #ifdef CONFIG_IP_VS_IPV6
1148         else
1149                 ip_vs_proc_conn(net, &param, flags, state, s->v6.protocol, af,
1150                                 (union nf_inet_addr *)&s->v6.daddr, s->v6.dport,
1151                                 ntohl(s->v6.timeout), ntohl(s->v6.fwmark),
1152                                 (opt_flags & IPVS_OPT_F_SEQ_DATA ? &opt : NULL)
1153                                 );
1154 #endif
1155         return 0;
1156         /* Error exit */
1157 out:
1158         IP_VS_DBG(2, "BACKUP, Single msg dropped err:%d\n", retc);
1159         return retc;
1160
1161 }
1162 /*
1163  *      Process received multicast message and create the corresponding
1164  *      ip_vs_conn entries.
1165  *      Handles Version 0 & 1
1166  */
1167 static void ip_vs_process_message(struct net *net, __u8 *buffer,
1168                                   const size_t buflen)
1169 {
1170         struct netns_ipvs *ipvs = net_ipvs(net);
1171         struct ip_vs_sync_mesg *m2 = (struct ip_vs_sync_mesg *)buffer;
1172         __u8 *p, *msg_end;
1173         int i, nr_conns;
1174
1175         if (buflen < sizeof(struct ip_vs_sync_mesg_v0)) {
1176                 IP_VS_DBG(2, "BACKUP, message header too short\n");
1177                 return;
1178         }
1179
1180         if (buflen != ntohs(m2->size)) {
1181                 IP_VS_DBG(2, "BACKUP, bogus message size\n");
1182                 return;
1183         }
1184         /* SyncID sanity check */
1185         if (ipvs->backup_syncid != 0 && m2->syncid != ipvs->backup_syncid) {
1186                 IP_VS_DBG(7, "BACKUP, Ignoring syncid = %d\n", m2->syncid);
1187                 return;
1188         }
1189         /* Handle version 1  message */
1190         if ((m2->version == SYNC_PROTO_VER) && (m2->reserved == 0)
1191             && (m2->spare == 0)) {
1192
1193                 msg_end = buffer + sizeof(struct ip_vs_sync_mesg);
1194                 nr_conns = m2->nr_conns;
1195
1196                 for (i=0; i<nr_conns; i++) {
1197                         union ip_vs_sync_conn *s;
1198                         unsigned int size;
1199                         int retc;
1200
1201                         p = msg_end;
1202                         if (p + sizeof(s->v4) > buffer+buflen) {
1203                                 IP_VS_ERR_RL("BACKUP, Dropping buffer, to small\n");
1204                                 return;
1205                         }
1206                         s = (union ip_vs_sync_conn *)p;
1207                         size = ntohs(s->v4.ver_size) & SVER_MASK;
1208                         msg_end = p + size;
1209                         /* Basic sanity checks */
1210                         if (msg_end  > buffer+buflen) {
1211                                 IP_VS_ERR_RL("BACKUP, Dropping buffer, msg > buffer\n");
1212                                 return;
1213                         }
1214                         if (ntohs(s->v4.ver_size) >> SVER_SHIFT) {
1215                                 IP_VS_ERR_RL("BACKUP, Dropping buffer, Unknown version %d\n",
1216                                               ntohs(s->v4.ver_size) >> SVER_SHIFT);
1217                                 return;
1218                         }
1219                         /* Process a single sync_conn */
1220                         retc = ip_vs_proc_sync_conn(net, p, msg_end);
1221                         if (retc < 0) {
1222                                 IP_VS_ERR_RL("BACKUP, Dropping buffer, Err: %d in decoding\n",
1223                                              retc);
1224                                 return;
1225                         }
1226                         /* Make sure we have 32 bit alignment */
1227                         msg_end = p + ((size + 3) & ~3);
1228                 }
1229         } else {
1230                 /* Old type of message */
1231                 ip_vs_process_message_v0(net, buffer, buflen);
1232                 return;
1233         }
1234 }
1235
1236
1237 /*
1238  *      Setup sndbuf (mode=1) or rcvbuf (mode=0)
1239  */
1240 static void set_sock_size(struct sock *sk, int mode, int val)
1241 {
1242         /* setsockopt(sock, SOL_SOCKET, SO_SNDBUF, &val, sizeof(val)); */
1243         /* setsockopt(sock, SOL_SOCKET, SO_RCVBUF, &val, sizeof(val)); */
1244         lock_sock(sk);
1245         if (mode) {
1246                 val = clamp_t(int, val, (SOCK_MIN_SNDBUF + 1) / 2,
1247                               sysctl_wmem_max);
1248                 sk->sk_sndbuf = val * 2;
1249                 sk->sk_userlocks |= SOCK_SNDBUF_LOCK;
1250         } else {
1251                 val = clamp_t(int, val, (SOCK_MIN_RCVBUF + 1) / 2,
1252                               sysctl_rmem_max);
1253                 sk->sk_rcvbuf = val * 2;
1254                 sk->sk_userlocks |= SOCK_RCVBUF_LOCK;
1255         }
1256         release_sock(sk);
1257 }
1258
1259 /*
1260  *      Setup loopback of outgoing multicasts on a sending socket
1261  */
1262 static void set_mcast_loop(struct sock *sk, u_char loop)
1263 {
1264         struct inet_sock *inet = inet_sk(sk);
1265
1266         /* setsockopt(sock, SOL_IP, IP_MULTICAST_LOOP, &loop, sizeof(loop)); */
1267         lock_sock(sk);
1268         inet->mc_loop = loop ? 1 : 0;
1269         release_sock(sk);
1270 }
1271
1272 /*
1273  *      Specify TTL for outgoing multicasts on a sending socket
1274  */
1275 static void set_mcast_ttl(struct sock *sk, u_char ttl)
1276 {
1277         struct inet_sock *inet = inet_sk(sk);
1278
1279         /* setsockopt(sock, SOL_IP, IP_MULTICAST_TTL, &ttl, sizeof(ttl)); */
1280         lock_sock(sk);
1281         inet->mc_ttl = ttl;
1282         release_sock(sk);
1283 }
1284
1285 /*
1286  *      Specifiy default interface for outgoing multicasts
1287  */
1288 static int set_mcast_if(struct sock *sk, char *ifname)
1289 {
1290         struct net_device *dev;
1291         struct inet_sock *inet = inet_sk(sk);
1292         struct net *net = sock_net(sk);
1293
1294         dev = __dev_get_by_name(net, ifname);
1295         if (!dev)
1296                 return -ENODEV;
1297
1298         if (sk->sk_bound_dev_if && dev->ifindex != sk->sk_bound_dev_if)
1299                 return -EINVAL;
1300
1301         lock_sock(sk);
1302         inet->mc_index = dev->ifindex;
1303         /*  inet->mc_addr  = 0; */
1304         release_sock(sk);
1305
1306         return 0;
1307 }
1308
1309
1310 /*
1311  *      Set the maximum length of sync message according to the
1312  *      specified interface's MTU.
1313  */
1314 static int set_sync_mesg_maxlen(struct net *net, int sync_state)
1315 {
1316         struct netns_ipvs *ipvs = net_ipvs(net);
1317         struct net_device *dev;
1318         int num;
1319
1320         if (sync_state == IP_VS_STATE_MASTER) {
1321                 dev = __dev_get_by_name(net, ipvs->master_mcast_ifn);
1322                 if (!dev)
1323                         return -ENODEV;
1324
1325                 num = (dev->mtu - sizeof(struct iphdr) -
1326                        sizeof(struct udphdr) -
1327                        SYNC_MESG_HEADER_LEN - 20) / SIMPLE_CONN_SIZE;
1328                 ipvs->send_mesg_maxlen = SYNC_MESG_HEADER_LEN +
1329                         SIMPLE_CONN_SIZE * min(num, MAX_CONNS_PER_SYNCBUFF);
1330                 IP_VS_DBG(7, "setting the maximum length of sync sending "
1331                           "message %d.\n", ipvs->send_mesg_maxlen);
1332         } else if (sync_state == IP_VS_STATE_BACKUP) {
1333                 dev = __dev_get_by_name(net, ipvs->backup_mcast_ifn);
1334                 if (!dev)
1335                         return -ENODEV;
1336
1337                 ipvs->recv_mesg_maxlen = dev->mtu -
1338                         sizeof(struct iphdr) - sizeof(struct udphdr);
1339                 IP_VS_DBG(7, "setting the maximum length of sync receiving "
1340                           "message %d.\n", ipvs->recv_mesg_maxlen);
1341         }
1342
1343         return 0;
1344 }
1345
1346
1347 /*
1348  *      Join a multicast group.
1349  *      the group is specified by a class D multicast address 224.0.0.0/8
1350  *      in the in_addr structure passed in as a parameter.
1351  */
1352 static int
1353 join_mcast_group(struct sock *sk, struct in_addr *addr, char *ifname)
1354 {
1355         struct net *net = sock_net(sk);
1356         struct ip_mreqn mreq;
1357         struct net_device *dev;
1358         int ret;
1359
1360         memset(&mreq, 0, sizeof(mreq));
1361         memcpy(&mreq.imr_multiaddr, addr, sizeof(struct in_addr));
1362
1363         dev = __dev_get_by_name(net, ifname);
1364         if (!dev)
1365                 return -ENODEV;
1366         if (sk->sk_bound_dev_if && dev->ifindex != sk->sk_bound_dev_if)
1367                 return -EINVAL;
1368
1369         mreq.imr_ifindex = dev->ifindex;
1370
1371         lock_sock(sk);
1372         ret = ip_mc_join_group(sk, &mreq);
1373         release_sock(sk);
1374
1375         return ret;
1376 }
1377
1378
1379 static int bind_mcastif_addr(struct socket *sock, char *ifname)
1380 {
1381         struct net *net = sock_net(sock->sk);
1382         struct net_device *dev;
1383         __be32 addr;
1384         struct sockaddr_in sin;
1385
1386         dev = __dev_get_by_name(net, ifname);
1387         if (!dev)
1388                 return -ENODEV;
1389
1390         addr = inet_select_addr(dev, 0, RT_SCOPE_UNIVERSE);
1391         if (!addr)
1392                 pr_err("You probably need to specify IP address on "
1393                        "multicast interface.\n");
1394
1395         IP_VS_DBG(7, "binding socket with (%s) %pI4\n",
1396                   ifname, &addr);
1397
1398         /* Now bind the socket with the address of multicast interface */
1399         sin.sin_family       = AF_INET;
1400         sin.sin_addr.s_addr  = addr;
1401         sin.sin_port         = 0;
1402
1403         return sock->ops->bind(sock, (struct sockaddr*)&sin, sizeof(sin));
1404 }
1405
1406 /*
1407  *      Set up sending multicast socket over UDP
1408  */
1409 static struct socket *make_send_sock(struct net *net, int id)
1410 {
1411         struct netns_ipvs *ipvs = net_ipvs(net);
1412         /* multicast addr */
1413         struct sockaddr_in mcast_addr = {
1414                 .sin_family             = AF_INET,
1415                 .sin_port               = cpu_to_be16(IP_VS_SYNC_PORT + id),
1416                 .sin_addr.s_addr        = cpu_to_be32(IP_VS_SYNC_GROUP),
1417         };
1418         struct socket *sock;
1419         int result;
1420
1421         /* First create a socket move it to right name space later */
1422         result = sock_create_kern(PF_INET, SOCK_DGRAM, IPPROTO_UDP, &sock);
1423         if (result < 0) {
1424                 pr_err("Error during creation of socket; terminating\n");
1425                 return ERR_PTR(result);
1426         }
1427         /*
1428          * Kernel sockets that are a part of a namespace, should not
1429          * hold a reference to a namespace in order to allow to stop it.
1430          * After sk_change_net should be released using sk_release_kernel.
1431          */
1432         sk_change_net(sock->sk, net);
1433         result = set_mcast_if(sock->sk, ipvs->master_mcast_ifn);
1434         if (result < 0) {
1435                 pr_err("Error setting outbound mcast interface\n");
1436                 goto error;
1437         }
1438
1439         set_mcast_loop(sock->sk, 0);
1440         set_mcast_ttl(sock->sk, 1);
1441         result = sysctl_sync_sock_size(ipvs);
1442         if (result > 0)
1443                 set_sock_size(sock->sk, 1, result);
1444
1445         result = bind_mcastif_addr(sock, ipvs->master_mcast_ifn);
1446         if (result < 0) {
1447                 pr_err("Error binding address of the mcast interface\n");
1448                 goto error;
1449         }
1450
1451         result = sock->ops->connect(sock, (struct sockaddr *) &mcast_addr,
1452                         sizeof(struct sockaddr), 0);
1453         if (result < 0) {
1454                 pr_err("Error connecting to the multicast addr\n");
1455                 goto error;
1456         }
1457
1458         return sock;
1459
1460 error:
1461         sk_release_kernel(sock->sk);
1462         return ERR_PTR(result);
1463 }
1464
1465
1466 /*
1467  *      Set up receiving multicast socket over UDP
1468  */
1469 static struct socket *make_receive_sock(struct net *net, int id)
1470 {
1471         struct netns_ipvs *ipvs = net_ipvs(net);
1472         /* multicast addr */
1473         struct sockaddr_in mcast_addr = {
1474                 .sin_family             = AF_INET,
1475                 .sin_port               = cpu_to_be16(IP_VS_SYNC_PORT + id),
1476                 .sin_addr.s_addr        = cpu_to_be32(IP_VS_SYNC_GROUP),
1477         };
1478         struct socket *sock;
1479         int result;
1480
1481         /* First create a socket */
1482         result = sock_create_kern(PF_INET, SOCK_DGRAM, IPPROTO_UDP, &sock);
1483         if (result < 0) {
1484                 pr_err("Error during creation of socket; terminating\n");
1485                 return ERR_PTR(result);
1486         }
1487         /*
1488          * Kernel sockets that are a part of a namespace, should not
1489          * hold a reference to a namespace in order to allow to stop it.
1490          * After sk_change_net should be released using sk_release_kernel.
1491          */
1492         sk_change_net(sock->sk, net);
1493         /* it is equivalent to the REUSEADDR option in user-space */
1494         sock->sk->sk_reuse = SK_CAN_REUSE;
1495         result = sysctl_sync_sock_size(ipvs);
1496         if (result > 0)
1497                 set_sock_size(sock->sk, 0, result);
1498
1499         result = sock->ops->bind(sock, (struct sockaddr *) &mcast_addr,
1500                         sizeof(struct sockaddr));
1501         if (result < 0) {
1502                 pr_err("Error binding to the multicast addr\n");
1503                 goto error;
1504         }
1505
1506         /* join the multicast group */
1507         result = join_mcast_group(sock->sk,
1508                         (struct in_addr *) &mcast_addr.sin_addr,
1509                         ipvs->backup_mcast_ifn);
1510         if (result < 0) {
1511                 pr_err("Error joining to the multicast group\n");
1512                 goto error;
1513         }
1514
1515         return sock;
1516
1517 error:
1518         sk_release_kernel(sock->sk);
1519         return ERR_PTR(result);
1520 }
1521
1522
1523 static int
1524 ip_vs_send_async(struct socket *sock, const char *buffer, const size_t length)
1525 {
1526         struct msghdr   msg = {.msg_flags = MSG_DONTWAIT|MSG_NOSIGNAL};
1527         struct kvec     iov;
1528         int             len;
1529
1530         EnterFunction(7);
1531         iov.iov_base     = (void *)buffer;
1532         iov.iov_len      = length;
1533
1534         len = kernel_sendmsg(sock, &msg, &iov, 1, (size_t)(length));
1535
1536         LeaveFunction(7);
1537         return len;
1538 }
1539
1540 static int
1541 ip_vs_send_sync_msg(struct socket *sock, struct ip_vs_sync_mesg *msg)
1542 {
1543         int msize;
1544         int ret;
1545
1546         msize = ntohs(msg->size);
1547
1548         ret = ip_vs_send_async(sock, (char *)msg, msize);
1549         if (ret >= 0 || ret == -EAGAIN)
1550                 return ret;
1551         pr_err("ip_vs_send_async error %d\n", ret);
1552         return 0;
1553 }
1554
1555 static int
1556 ip_vs_receive(struct socket *sock, char *buffer, const size_t buflen)
1557 {
1558         struct msghdr           msg = {NULL,};
1559         struct kvec             iov;
1560         int                     len;
1561
1562         EnterFunction(7);
1563
1564         /* Receive a packet */
1565         iov.iov_base     = buffer;
1566         iov.iov_len      = (size_t)buflen;
1567
1568         len = kernel_recvmsg(sock, &msg, &iov, 1, buflen, MSG_DONTWAIT);
1569
1570         if (len < 0)
1571                 return len;
1572
1573         LeaveFunction(7);
1574         return len;
1575 }
1576
1577 /* Wakeup the master thread for sending */
1578 static void master_wakeup_work_handler(struct work_struct *work)
1579 {
1580         struct ipvs_master_sync_state *ms =
1581                 container_of(work, struct ipvs_master_sync_state,
1582                              master_wakeup_work.work);
1583         struct netns_ipvs *ipvs = ms->ipvs;
1584
1585         spin_lock_bh(&ipvs->sync_lock);
1586         if (ms->sync_queue_len &&
1587             ms->sync_queue_delay < IPVS_SYNC_WAKEUP_RATE) {
1588                 ms->sync_queue_delay = IPVS_SYNC_WAKEUP_RATE;
1589                 wake_up_process(ms->master_thread);
1590         }
1591         spin_unlock_bh(&ipvs->sync_lock);
1592 }
1593
1594 /* Get next buffer to send */
1595 static inline struct ip_vs_sync_buff *
1596 next_sync_buff(struct netns_ipvs *ipvs, struct ipvs_master_sync_state *ms)
1597 {
1598         struct ip_vs_sync_buff *sb;
1599
1600         sb = sb_dequeue(ipvs, ms);
1601         if (sb)
1602                 return sb;
1603         /* Do not delay entries in buffer for more than 2 seconds */
1604         return get_curr_sync_buff(ipvs, ms, IPVS_SYNC_FLUSH_TIME);
1605 }
1606
1607 static int sync_thread_master(void *data)
1608 {
1609         struct ip_vs_sync_thread_data *tinfo = data;
1610         struct netns_ipvs *ipvs = net_ipvs(tinfo->net);
1611         struct ipvs_master_sync_state *ms = &ipvs->ms[tinfo->id];
1612         struct sock *sk = tinfo->sock->sk;
1613         struct ip_vs_sync_buff *sb;
1614
1615         pr_info("sync thread started: state = MASTER, mcast_ifn = %s, "
1616                 "syncid = %d, id = %d\n",
1617                 ipvs->master_mcast_ifn, ipvs->master_syncid, tinfo->id);
1618
1619         for (;;) {
1620                 sb = next_sync_buff(ipvs, ms);
1621                 if (unlikely(kthread_should_stop()))
1622                         break;
1623                 if (!sb) {
1624                         schedule_timeout(IPVS_SYNC_CHECK_PERIOD);
1625                         continue;
1626                 }
1627                 while (ip_vs_send_sync_msg(tinfo->sock, sb->mesg) < 0) {
1628                         int ret = 0;
1629
1630                         __wait_event_interruptible(*sk_sleep(sk),
1631                                                    sock_writeable(sk) ||
1632                                                    kthread_should_stop(),
1633                                                    ret);
1634                         if (unlikely(kthread_should_stop()))
1635                                 goto done;
1636                 }
1637                 ip_vs_sync_buff_release(sb);
1638         }
1639
1640 done:
1641         __set_current_state(TASK_RUNNING);
1642         if (sb)
1643                 ip_vs_sync_buff_release(sb);
1644
1645         /* clean up the sync_buff queue */
1646         while ((sb = sb_dequeue(ipvs, ms)))
1647                 ip_vs_sync_buff_release(sb);
1648         __set_current_state(TASK_RUNNING);
1649
1650         /* clean up the current sync_buff */
1651         sb = get_curr_sync_buff(ipvs, ms, 0);
1652         if (sb)
1653                 ip_vs_sync_buff_release(sb);
1654
1655         /* release the sending multicast socket */
1656         sk_release_kernel(tinfo->sock->sk);
1657         kfree(tinfo);
1658
1659         return 0;
1660 }
1661
1662
1663 static int sync_thread_backup(void *data)
1664 {
1665         struct ip_vs_sync_thread_data *tinfo = data;
1666         struct netns_ipvs *ipvs = net_ipvs(tinfo->net);
1667         int len;
1668
1669         pr_info("sync thread started: state = BACKUP, mcast_ifn = %s, "
1670                 "syncid = %d, id = %d\n",
1671                 ipvs->backup_mcast_ifn, ipvs->backup_syncid, tinfo->id);
1672
1673         while (!kthread_should_stop()) {
1674                 wait_event_interruptible(*sk_sleep(tinfo->sock->sk),
1675                          !skb_queue_empty(&tinfo->sock->sk->sk_receive_queue)
1676                          || kthread_should_stop());
1677
1678                 /* do we have data now? */
1679                 while (!skb_queue_empty(&(tinfo->sock->sk->sk_receive_queue))) {
1680                         len = ip_vs_receive(tinfo->sock, tinfo->buf,
1681                                         ipvs->recv_mesg_maxlen);
1682                         if (len <= 0) {
1683                                 if (len != -EAGAIN)
1684                                         pr_err("receiving message error\n");
1685                                 break;
1686                         }
1687
1688                         ip_vs_process_message(tinfo->net, tinfo->buf, len);
1689                 }
1690         }
1691
1692         /* release the sending multicast socket */
1693         sk_release_kernel(tinfo->sock->sk);
1694         kfree(tinfo->buf);
1695         kfree(tinfo);
1696
1697         return 0;
1698 }
1699
1700
1701 int start_sync_thread(struct net *net, int state, char *mcast_ifn, __u8 syncid)
1702 {
1703         struct ip_vs_sync_thread_data *tinfo;
1704         struct task_struct **array = NULL, *task;
1705         struct socket *sock;
1706         struct netns_ipvs *ipvs = net_ipvs(net);
1707         char *name;
1708         int (*threadfn)(void *data);
1709         int id, count;
1710         int result = -ENOMEM;
1711
1712         IP_VS_DBG(7, "%s(): pid %d\n", __func__, task_pid_nr(current));
1713         IP_VS_DBG(7, "Each ip_vs_sync_conn entry needs %Zd bytes\n",
1714                   sizeof(struct ip_vs_sync_conn_v0));
1715
1716         if (!ipvs->sync_state) {
1717                 count = clamp(sysctl_sync_ports(ipvs), 1, IPVS_SYNC_PORTS_MAX);
1718                 ipvs->threads_mask = count - 1;
1719         } else
1720                 count = ipvs->threads_mask + 1;
1721
1722         if (state == IP_VS_STATE_MASTER) {
1723                 if (ipvs->ms)
1724                         return -EEXIST;
1725
1726                 strlcpy(ipvs->master_mcast_ifn, mcast_ifn,
1727                         sizeof(ipvs->master_mcast_ifn));
1728                 ipvs->master_syncid = syncid;
1729                 name = "ipvs-m:%d:%d";
1730                 threadfn = sync_thread_master;
1731         } else if (state == IP_VS_STATE_BACKUP) {
1732                 if (ipvs->backup_threads)
1733                         return -EEXIST;
1734
1735                 strlcpy(ipvs->backup_mcast_ifn, mcast_ifn,
1736                         sizeof(ipvs->backup_mcast_ifn));
1737                 ipvs->backup_syncid = syncid;
1738                 name = "ipvs-b:%d:%d";
1739                 threadfn = sync_thread_backup;
1740         } else {
1741                 return -EINVAL;
1742         }
1743
1744         if (state == IP_VS_STATE_MASTER) {
1745                 struct ipvs_master_sync_state *ms;
1746
1747                 ipvs->ms = kzalloc(count * sizeof(ipvs->ms[0]), GFP_KERNEL);
1748                 if (!ipvs->ms)
1749                         goto out;
1750                 ms = ipvs->ms;
1751                 for (id = 0; id < count; id++, ms++) {
1752                         INIT_LIST_HEAD(&ms->sync_queue);
1753                         ms->sync_queue_len = 0;
1754                         ms->sync_queue_delay = 0;
1755                         INIT_DELAYED_WORK(&ms->master_wakeup_work,
1756                                           master_wakeup_work_handler);
1757                         ms->ipvs = ipvs;
1758                 }
1759         } else {
1760                 array = kzalloc(count * sizeof(struct task_struct *),
1761                                 GFP_KERNEL);
1762                 if (!array)
1763                         goto out;
1764         }
1765         set_sync_mesg_maxlen(net, state);
1766
1767         tinfo = NULL;
1768         for (id = 0; id < count; id++) {
1769                 if (state == IP_VS_STATE_MASTER)
1770                         sock = make_send_sock(net, id);
1771                 else
1772                         sock = make_receive_sock(net, id);
1773                 if (IS_ERR(sock)) {
1774                         result = PTR_ERR(sock);
1775                         goto outtinfo;
1776                 }
1777                 tinfo = kmalloc(sizeof(*tinfo), GFP_KERNEL);
1778                 if (!tinfo)
1779                         goto outsocket;
1780                 tinfo->net = net;
1781                 tinfo->sock = sock;
1782                 if (state == IP_VS_STATE_BACKUP) {
1783                         tinfo->buf = kmalloc(ipvs->recv_mesg_maxlen,
1784                                              GFP_KERNEL);
1785                         if (!tinfo->buf)
1786                                 goto outtinfo;
1787                 } else {
1788                         tinfo->buf = NULL;
1789                 }
1790                 tinfo->id = id;
1791
1792                 task = kthread_run(threadfn, tinfo, name, ipvs->gen, id);
1793                 if (IS_ERR(task)) {
1794                         result = PTR_ERR(task);
1795                         goto outtinfo;
1796                 }
1797                 tinfo = NULL;
1798                 if (state == IP_VS_STATE_MASTER)
1799                         ipvs->ms[id].master_thread = task;
1800                 else
1801                         array[id] = task;
1802         }
1803
1804         /* mark as active */
1805
1806         if (state == IP_VS_STATE_BACKUP)
1807                 ipvs->backup_threads = array;
1808         spin_lock_bh(&ipvs->sync_buff_lock);
1809         ipvs->sync_state |= state;
1810         spin_unlock_bh(&ipvs->sync_buff_lock);
1811
1812         /* increase the module use count */
1813         ip_vs_use_count_inc();
1814
1815         return 0;
1816
1817 outsocket:
1818         sk_release_kernel(sock->sk);
1819
1820 outtinfo:
1821         if (tinfo) {
1822                 sk_release_kernel(tinfo->sock->sk);
1823                 kfree(tinfo->buf);
1824                 kfree(tinfo);
1825         }
1826         count = id;
1827         while (count-- > 0) {
1828                 if (state == IP_VS_STATE_MASTER)
1829                         kthread_stop(ipvs->ms[count].master_thread);
1830                 else
1831                         kthread_stop(array[count]);
1832         }
1833         kfree(array);
1834
1835 out:
1836         if (!(ipvs->sync_state & IP_VS_STATE_MASTER)) {
1837                 kfree(ipvs->ms);
1838                 ipvs->ms = NULL;
1839         }
1840         return result;
1841 }
1842
1843
1844 int stop_sync_thread(struct net *net, int state)
1845 {
1846         struct netns_ipvs *ipvs = net_ipvs(net);
1847         struct task_struct **array;
1848         int id;
1849         int retc = -EINVAL;
1850
1851         IP_VS_DBG(7, "%s(): pid %d\n", __func__, task_pid_nr(current));
1852
1853         if (state == IP_VS_STATE_MASTER) {
1854                 if (!ipvs->ms)
1855                         return -ESRCH;
1856
1857                 /*
1858                  * The lock synchronizes with sb_queue_tail(), so that we don't
1859                  * add sync buffers to the queue, when we are already in
1860                  * progress of stopping the master sync daemon.
1861                  */
1862
1863                 spin_lock_bh(&ipvs->sync_buff_lock);
1864                 spin_lock(&ipvs->sync_lock);
1865                 ipvs->sync_state &= ~IP_VS_STATE_MASTER;
1866                 spin_unlock(&ipvs->sync_lock);
1867                 spin_unlock_bh(&ipvs->sync_buff_lock);
1868
1869                 retc = 0;
1870                 for (id = ipvs->threads_mask; id >= 0; id--) {
1871                         struct ipvs_master_sync_state *ms = &ipvs->ms[id];
1872                         int ret;
1873
1874                         pr_info("stopping master sync thread %d ...\n",
1875                                 task_pid_nr(ms->master_thread));
1876                         cancel_delayed_work_sync(&ms->master_wakeup_work);
1877                         ret = kthread_stop(ms->master_thread);
1878                         if (retc >= 0)
1879                                 retc = ret;
1880                 }
1881                 kfree(ipvs->ms);
1882                 ipvs->ms = NULL;
1883         } else if (state == IP_VS_STATE_BACKUP) {
1884                 if (!ipvs->backup_threads)
1885                         return -ESRCH;
1886
1887                 ipvs->sync_state &= ~IP_VS_STATE_BACKUP;
1888                 array = ipvs->backup_threads;
1889                 retc = 0;
1890                 for (id = ipvs->threads_mask; id >= 0; id--) {
1891                         int ret;
1892
1893                         pr_info("stopping backup sync thread %d ...\n",
1894                                 task_pid_nr(array[id]));
1895                         ret = kthread_stop(array[id]);
1896                         if (retc >= 0)
1897                                 retc = ret;
1898                 }
1899                 kfree(array);
1900                 ipvs->backup_threads = NULL;
1901         }
1902
1903         /* decrease the module use count */
1904         ip_vs_use_count_dec();
1905
1906         return retc;
1907 }
1908
1909 /*
1910  * Initialize data struct for each netns
1911  */
1912 int __net_init ip_vs_sync_net_init(struct net *net)
1913 {
1914         struct netns_ipvs *ipvs = net_ipvs(net);
1915
1916         __mutex_init(&ipvs->sync_mutex, "ipvs->sync_mutex", &__ipvs_sync_key);
1917         spin_lock_init(&ipvs->sync_lock);
1918         spin_lock_init(&ipvs->sync_buff_lock);
1919         return 0;
1920 }
1921
1922 void ip_vs_sync_net_cleanup(struct net *net)
1923 {
1924         int retc;
1925         struct netns_ipvs *ipvs = net_ipvs(net);
1926
1927         mutex_lock(&ipvs->sync_mutex);
1928         retc = stop_sync_thread(net, IP_VS_STATE_MASTER);
1929         if (retc && retc != -ESRCH)
1930                 pr_err("Failed to stop Master Daemon\n");
1931
1932         retc = stop_sync_thread(net, IP_VS_STATE_BACKUP);
1933         if (retc && retc != -ESRCH)
1934                 pr_err("Failed to stop Backup Daemon\n");
1935         mutex_unlock(&ipvs->sync_mutex);
1936 }